AJAX Not Working Without Alert Box
Solution 1:
The reason it works when you introduce the alert is because it stops execution and gives enough time for the asynchronous call to finish.
You're not getting the right value because by the time the post request is finished and the callback is executed your javascript has already finished executing.
You have a few options here:
- Declare a global variable and perform a synchronous call, you can either do it with the code ABC posted or call
$.ajaxSetup({ async: false })
before your POST call. Assign the return value to the global variable and validate against that. - use jQuery's ajaxStop:
$(document).ajaxStop(function() { //check your values here, still need to declare a global });
- Write the value to a hidden div/as an attribute anywhere in the DOM and have a timer that periodically checks it until there's a value.
Solution 2:
in your code the ajax call is working asynchronous, so no matter you are responded or not your next lines will be executed. In sync call your next lines will not be executed untill you get response. you could turn into $.ajax from $.post and make async property false. Then you will be able to get and then you can get the value of "reply" after the ajax call is responded.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});
Solution 3:
A new thought came to my mind, please check this.
/**
* form submit
*/
$('#form1').on('submit', function() {
if (checkExistence()) {
return false;
}
});
/**
* check existence in db
* @returns {Boolean}
*/
function checkExistence() {
var txtItemCode = $('#txtItemCode').val();
var result = true;
$.post("http://localhost/test.php", {
txtItemCode: txtItemCode,
}, function(data, status) {
//alert("Data: " + data + "\nStatus: " + status);
if (data == 'OK') {
$('#status').html(data);
result = true;
} else {
$('#txtItemCode').val('').focus();
$('#status').html("Code is already existing, please provide another one:)")
result = false;
}
});
return result;
}
Note: You can swap the value of result and check.
Post a Comment for "AJAX Not Working Without Alert Box"