[Solved-6 Solutions] jQuery to perform a synchronous, rather than asynchronous, Ajax request - javascript tutorial



Problem:

How to get jQuery to perform a synchronous, rather than asynchronous, Ajax request ?

Solution 1:

To implement a synchronous request, change the third parameter in the open () method to false:

xhttp.open("GET", "ajax_info.txt", false);

async = false are used for quick testing. You will also find synchronous requests in older JavaScript code. Since the code will wait for server completion, there is no need for an onreadystatechange function:

xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;

Synchronous XMLHttpRequest (async = false) is not suggested because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will suspend or stop.

Solution 2:

beforecreate: function (node, targetNode, type, to) {
  jQuery.get('http://wikitechy.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),

  function (result) {
    if (result.isOk == false) 
        alert(result.message);
  });
}

Solution 3:

beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
        url: 'http://wikitechy.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: false
    });
}

Solution 4:

We can set the jQuery's Ajax setup in synchronous mode by calling

jQuery.ajaxSetup({async:false});

and then perform your Ajax calls using jQuery.get( ... ); then just turning it on again once

jQuery.ajaxSetup({async:true});

It might be useful to somebody that does want to reconfigure their jQuery.get() or jQuery.post() to the additional elaborate jQuery.ajax() syntax.

Solution 5:

function getWhatever() {
  // strUrl is whatever URL you need to call
  var strUrl = "", strReturn = "";

  jQuery.ajax({
    url: strUrl,
    success: function(html) {
      strReturn = html;
    },
    async:false
  });

  return strReturn;
}

Solution 6:

beforecreate: function(node,targetNode,type,to) {

    Frame(function(next)){

        jQuery.get('http://wikitechy.com/catalog/create/', next);
    });

    Frame(function(next, response)){

        alert(response);
        next();
    });

    Frame.init();
}


Related Searches to jQuery to perform a synchronous, rather than asynchronous, Ajax request - javascript tutorial