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?
CompanyName: $('#CompanyName').val(),and what isGetDateTimeNow()