2

this is my web API method :

[HttpPost] public ActionResult InsertCompany(Company value) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.PostAsJsonAsync($"{WebConfigurationManager.AppSettings["URL"]}/Company/InsertCompany", value).Result; if (response.IsSuccessStatusCode) { return Json(new { success = true, responseText = "Data berhasil ditambahkan!" }, JsonRequestBehavior.AllowGet); } } return Json(new { success = false, responseText = "Data gagal ditambahkan!" }, JsonRequestBehavior.AllowGet); } 

and this is my ajax call :

function PostData() { $.ajax ({ url: 'InsertCompany', type: 'POST', dataType: 'json', data: { CompanyName: $('#CompanyName').val(), JoinDate: GetDateTimeNow() }, success: function (response) { if (response !== null && response.success) { location.reload(); alert(response.responseText); } else { alert(response.responseText); } }, error: function (response) { alert('error: ' + response.responseText); // } }); } 

this is how I call the ajax :

$('#btnSubmit').click(function () { PostData(); }); 

this is GetDateTimeNow() method :

function GetDateTimeNow() { var date = new Date(); var day = date.getDate(); // yields date var month = date.getMonth() + 1; // yields month (add one as '.getMonth()' is zero indexed) var year = date.getFullYear(); // yields year var hour = date.getHours(); // yields hours var minute = date.getMinutes(); // yields minutes var second = date.getSeconds(); // yields seconds // After this construct a string with the above results as below var time = day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second; return time; } 

this is my html element :

<button type="submit" class="btn btn-primary" id="btnSubmit">Submit</button> <input type="text" class="form-control" id="CompanyName" placeholder="Enter Company Name"> 

this is response for the first time i call ajax:

error: undefined

and this is the second response and so on for the ajax call :

Data berhasil ditambahkan!

my question is why my ajax call not success only on the first time I call after load page? but success on the second time and so on, any idea what happen?

8
  • 1
    how you are doing ajax call(which code is calling ajax)? that code needed, and if it have some html too then that html code also needed Commented Aug 3, 2017 at 6:26
  • @AlivetoDie I'm doing it in button click event using jquery, that first call is not returning 200, so it goes to error, but on the second call and so on it returning 200.. i don't understand Commented Aug 3, 2017 at 6:30
  • 1
    please update that html+calling code here also (in your question),then only may be some-one can help Commented Aug 3, 2017 at 6:36
  • @AlivetoDie I already updated my question with html+calling code, any ideas what happen? Commented Aug 3, 2017 at 6:43
  • Still html is not full,because i don't know how you get this:- CompanyName: $('#CompanyName').val(), and what is GetDateTimeNow() Commented Aug 3, 2017 at 6:52

1 Answer 1

1

Two changes needed:-

1.Use e.preventDefault();:-

$('#btnSubmit').click(function (e) { e.preventDefault();PostData(); }); 

2.Check that company name not empty then only do the ajax call:-

function PostData() { if($.trim($('#CompanyName').val()) != ''){ //put your complete ajax call code inside it } } 

Note:-

problem arise when you hit submit without checking company name is having value or not? an empty data goes via ajax call and you got undefined.

preventDefault() is just use to stop normal posting(Page refresh) of the form (if you have), when you click button.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks man it works! but I still don't understand.. I never left CompanyName without value, I always assign value to company name because before I hit submit button I type company name first then hit the submit button..
May be you din't use e.preventDefault(); so button click event not triggering or normal page refresh happening.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.