Skip to content Skip to sidebar Skip to footer

Ajax Complete Handler In Pure Js

I am using AJAX in pure Javascript which returns false if failed else returns a json data: var responsefromURL = loadAjaX(url); if(responsefromURL != false) { a

Solution 1:

Let us assume this is your AJAX function:

functionloadAjaX(url, callback)
{
    var ajax;
    if (window.XMLHttpRequest)  {
        ajax = newXMLHttpRequest();
    } else {
        ajax = newActiveXObject("Microsoft.XMLHTTP");
    }
    ajax.onreadystatechange = function() {
        if (ajax.readyState==4 && ajax.status==200) {
            callback(ajax.responseText);
        }
    }
    ajax.open("GET",url,true);
    ajax.send();
}

Now you can call your callback method with the response on complete:

loadAjaX(url, callback);

Solution 2:

Try this:

var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=newXMLHttpRequest();
  }
else
  {
  xmlhttp=newActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    var responsefromURL = xmlhttp.responseText;
    if(responsefromURL != false)
    {
        alert("Failed to fetch Data from URL. (Store/Store)");
    }
    else
    {
var responseJSON = eval('('+responsefromURL+')');        
this.prepareStoreFromJSON(responseJSON);
    }
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();

Solution 3:

you can set a function on the onreadystatechange property.

see documentation http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

example

varCOMPLETE = 4;
var xmlhttp = newXMLHttpRequest();
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange=function() {

    // if complete and status 200if (xmlhttp.readyState == COMPLETE && xmlhttp.status == 200) {
        if (xmlhttp.responseText != null) {
            prepareStoreFromJSON(xmlhttp.responseText);
        }
        else {
            alert("Failed to fetch Data from URL. (Store/Store)");
        }
    }
}

Post a Comment for "Ajax Complete Handler In Pure Js"