1

In jQuery, while something is loading I can do this:

$.ajax({
  url: "/answer_checker.php",
  global: false, type: "POST", 
  data: ({...clipped...}), 
  cache: false,
  beforeSend: function() {
    $('#response').html("<img src='/images/loading.gif' />");
  },
  success: function(html) {
    $('#response').html(html);
  }
}

How can I apply beforeSend and success in plain javascript? I currently have this:

function processGeneric() {
setTimeout(function () {
    if (xmlHttpObject.readyState === 0 || xmlHttpObject.readyState === 4) {
        xmlHttpObject.open("GET", requestLink, true);
        xmlHttpObject.onreadystatechange = function () {//some code to handle here};
        xmlHttpObject.send(null);
    }
}, timeout);
}
Legendary
  • 2,243
  • 16
  • 26
Alpha2k
  • 2,212
  • 7
  • 38
  • 65

1 Answers1

2

You create a function that accepts the callbacks you want along with other ajax options, and then have the function:

  1. Call the "before send" callback

  2. Make the ajax call, which is well-covered in this other question and its answers

  3. When the call is complete, call the completion callback

Something vaguely along these lines:

function processGeneric(url, beforeSend, completion) {
    var xhr;

    xhr = new XMLHttpRequest();
    xhr.onreadstatechange = function() {
        if (xhr.readyState === 0 || xhr.readyState === 4) {
            if (completion) {
                completion(xhr);
            }
            done();
        }
    };
    xhr.open("GET", url, true);
    if (beforeSend) {
        if (beforeSend(xhr) === false) {
            done();
            return;
        }
    }
    xhr.send(null);
    return xhr;

    function done() {
        xhr.onreadystatechange = null;
        xhr = undefined;
    }
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875