I have the following jQuery:
var fn = {
Load: function () {
$(".myclass input.Submit").click(function (e) {
var _IsValid = fn.IsValid();
if (_IsValid == false) {
e.preventDefault();
}
//Popup displays message fine if "return false;" is
//called here but then obviously never posts back.
});
}
, IsValid: function () {
var _IsValid = true;
$.ajax({
url: "/myURL"
, type: 'POST'
, contentType: 'application/json; charset=utf-8'
, data: JSON.stringify({ Barcode: $barcode.val(), Email: $email.val() })
, dataType: 'json'
, success: function (data) {
var array = eval(data);
if (array[0] == 0) {
_IsValid = false;
ShowPopup(array[1]);
}
}
, error: function (xhr, status, error) {
}
});
return _IsValid;
}
}
AJAX response is 200 OK, but the success function is not being ran. Instead it seems to be running the error function.
The script is being ran as an click event listener for an ASP.NET ImageButton. If _IsValid==false, then e.preventDefault() is invoked to prevent postback.
What’s strange is that if I add return false to the end of my event listener function, this code runs the success function.
How can I find out what is causing this to error so that I can resolve it?
I think the problem you currently have is that your
IsValidfunction will always return true. This is because the AJAX post will not have time to complete before the function is returned. It is an asynchronous function after all.From what I can tell you want to valid a form with an AJAX request and if valid submit the form, otherwise show a popup. If that is correct you should do something like…