Search code examples
javascriptjqueryscoping

Cant access variable inside jQuery $.post


I went through many posts about this, but didnt find any solution working for me - cleaned up code:

  $('#form-new').submit(function(e){
    e.preventDefault();

    $curForm = $(this);
    $textbox = $( '.new-box' ,this);

    window.tmp_input_ok = false;

    var wasError = false;
    if( $.trim($textbox.val()) == "" ){  
      wasError = true; 
    }    

    if( wasError ){
      //possible message
    } else{

      var jqxhr = $.post(
        $(this).attr('action'),
        $(this).serialize(),
        function(data, textStatus, jqXHR){

          if( data=="200" ){
            console.log('post OK'); //this shows in console!
            window.tmp_input_ok = true;  
          } else{
            console.log('not OK');       
          } 

        }
      ).fail(function() {
        console.log('POST fail)');
      });    

    }

    //however, window.tmp_input_ok is false here so the textbox does not empty:
    if(window.tmp_input_ok == true) $textbox.val(''); 
      else console.log('input not ok :('); //and this is outputted to console

  }); 

Originaly, there was just a var tmp_input_ok = false initialization and then working with the tmp_input_ok variable, but it wasnt working so I tried global window... does not work either... I am starting to be desperate.


Solution

  • Your if statement is executed before the call is finished.

    $.post is an async call and the rest of the code continues while the post is processing

    You are already using .fail(), you can add .always() if you want to execute your if statement always on completion or add it to your .success() if you only want to check it when the call succeeds, similar to this:

    if (wasError) {
        //possible message
    } else {
        var jqxhr = $.post($(this).attr('action'), $(this).serialize(), function (data, textStatus, jqXHR) {
            if (data == "200") {
                console.log('post OK'); //this shows in console!
                window.tmp_input_ok = true;
            } else {
                console.log('not OK');
            }
    
            // either add it here if you only want to process it on success
            if (window.tmp_input_ok == true) $textbox.val('');
            else console.log('input not ok :(');
        }).fail(function () {
            console.log('POST fail)');
        }).always(function(){ // or add it here if you always wan to execute on completion regardless of fail or success
            if (window.tmp_input_ok == true) $textbox.val('');
            else console.log('input not ok :(');
        });
    }