1

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?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
sam
  • 439
  • 1
  • 6
  • 11
  • If you post a complete example to jsfiddle that would be great, we really do need a little more info but you should have all the info you news in the thread right now – Mataniko Jul 05 '13 at 05:03
  • Have a look at this question: http://stackoverflow.com/q/16090545/218196, especially this answer: http://stackoverflow.com/a/16090709/218196. All the answer you got here are inferior IMO. – Felix Kling Jul 05 '13 at 07:03

3 Answers3

4

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.
Mataniko
  • 2,212
  • 16
  • 18
  • I think it quite curious that the JavaScript engine would let AJAX event handlers be called while an `alert` is in progress. – icktoofay Jul 05 '13 at 06:19
  • Yes it is working with your option one , add $.ajaxSetup({ async: false }) before POST call. Thanks for all help beginners . – sam Jul 05 '13 at 06:56
3

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
});
Mujtaba Haider
  • 1,650
  • 2
  • 19
  • 29
  • http://stackoverflow.com/questions/5528852/ajax-sync-and-async-difference – Mujtaba Haider Jul 05 '13 at 04:14
  • 1
    It'll work if it's synchronous, but it's a bad user experience. – icktoofay Jul 05 '13 at 04:15
  • the other way is you should reconstruct your code. and use done function of ajax – Mujtaba Haider Jul 05 '13 at 04:26
  • This is the right answer I'm sure,if you think it's a bad user experience,you can just use `beforeSend` to tell people it's still transferring,then remove it use `complete` – 5z- - Jul 05 '13 at 04:53
  • 1
    @5-T: No; synchronous AJAX queues block the UI thread. If you add an element in `beforeSend` and then do a synchronous AJAX call and then remove it, the element will never show up; you never released the UI thread to allow it to redraw the page. – icktoofay Jul 05 '13 at 04:57
  • Making synchronous requests can and should be avoided. – Felix Kling Jul 05 '13 at 07:04
  • @icktoofay please notice the function,he used `submit` to trigger the function, not `onload`,so the element will show up before user click the button to submit the form. – 5z- - Jul 05 '13 at 07:10
0

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.

Anjith K P
  • 2,158
  • 27
  • 35
  • 1
    This wouldn't work. Since Ajax is asynchronous, `checkExistence` will always return `true`. – Felix Kling Jul 05 '13 at 07:03
  • yeah, u are rigth. Then can use http://malsup.com/jquery/form/ form submit method instead of notmal form submit. – Anjith K P Jul 05 '13 at 07:06
  • This not work , your result is ok , but i need submit the form with data. the result comes to the #status but form is not submitting. – sam Jul 05 '13 at 07:19
  • You can use ajax form submit in both cases. Use jquery form submit (http://malsup.com/jquery/form/) for submitting form instead of normal form submit. This will hel you. – Anjith K P Jul 05 '13 at 07:22