AJAX not working without alert box [duplicate]

I'm trying to use this code:

$('#form1').on('submit', function(){
    var txtItemCode = $('#txtItemCode').val();
    $.post("userExist.php", {
        txtItemCode: txtItemCode,
    }, function(data,status){
        //alert("Data: " + data + "\nStatus: " + status);
        $('#status').html(data);    
        reply = data;
        //alert(reply);
    });
    alert('');
    if (reply=='OK'){
        return false;
    }
});

I need to check if data=="OK" and return false, but when I remove the alert, it no longer works. Why is this, and how can I make it work?

Answers:

Answer

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:

  1. 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.
  2. use jQuery's ajaxStop: $(document).ajaxStop(function() { //check your values here, still need to declare a global });
  3. 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.
Answer

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
});
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.