Search code examples
javascriptjqueryajaxcallbackjquery-callback

How to fashion callback for results of JQuery/AJAX 'get' routine


I've read and re-read every first-page Google result on JQuery/AJAX callbacks using every permutation of terms I can think of, and no re-write I've tried for the code below is successful.

I simply need to construct a callback for this function—which is part of a larger self-calling JQuery function—so that the 'message' variable holds the results of the integrity_check.php routine before proceding to the evaluation routine of 'message' at the end.

(Yes, this is yet another attempt to make JQuery synchronous, and I understand that callbacks are the answer, but I can't find it.) May success and happiness befall you if you can help me with this:

// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
$.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
    if (data != 0) {
        message = data;
    }
});

[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]

if (message != '') {
    alert(message);
} else {
    [...proceed with using new_variable in HTML...]
}

UPDATE

The suggestion by Guest271314 pointed in the right direction, although I had to make modifications to make it work; see CAPS commentary in code solution that follows:

var request = $.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
    if (data != 0) {
        message = data;
    } 
    return message;
});

// HERE I HAD TO SAVE THIS VALUE TO A NEW VARIABLE; 
// $('#new_variable').val(); WAS NOT ACCESSIBLE OTHERWISE IN THE ROUTINE THAT FOLLOWED:
var nv = $('#new_variable').val();

// HERE IT WAS IRRELEVANT WHAT ARGUMENT WENT INTO function(),
// EXCEPT IT COULD *NOT* BE message; YOU HAD SUGGESTED msg, WHICH WAS IMMATERIAL, IT TURNED OUT
request.then(function() {

    // HERE I *HAD* TO USE message, NOT THE GENERIC msg THAT YOU HAD PASSED INTO THE FUNCTION:
    if (message != '') {
        alert(message);
    } else {

        // THE ORIGINAL FORM HERE WOULDN'T WORK, AS $('#new_variable').val() WAS INACCESSIBLE IN THE FUNCTION:
        //var newKeyword = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + $('#new_variable').val() + '" checked /> ' + $('#new_variable').val() + '</label>';

        // THIS, HOWEVER, WORKED...USING nv IN PLACE OF $('#new_variable').val();
        var newVariable = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + nv + '" checked /> ' + nv + '</label>';

        $('#checkboxes').append(newVariable);
    }
});

I'm grateful to guest271314 for what s/he posted, although I'm unclear on why I had to make the changes that I did in order for the code to work. Elucidation, anyone?


Solution

  • Try utilizing deferred.then()

    // If the integrity check passed, message will be empty.
    // If the integrity check fails, message will hold text for an alert box.
    var message;
    var request = $.get('integrity_check.php'
                  , { add_new_variable: $('#new_variable').val() }
                  , function(data) {
                      if (data != 0) {
                        message = data;                    
                      }
                      return message
                  });
    /*
    [...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
    */
    request.then(function(msg) {
      // `msg`: `message`
      if (msg != '') {
        alert(msg);
      } else {
        // [...proceed with using new_variable in HTML...]        
      }
      // return msg
    }, function err(jqxhr, textStaus, errorThrown) {
         console.log(errorThrown)
    });