2

here is my ajaxHandler i want to convert this to native javascript i.e using XMLHttpRequest but i am unable to understand how to convert.`

ajaxHandler = {
  defaultAttributes: {
    type: 'GET',
    url: 'index.php/request',
    datatype: 'json',
    data: {},
    success: null,
    error: function(data) {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
    },
    timeout: function() {
      errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
    }
  },
  sendRequest: function(attributes) {
    Paper.giffyLoading.style.display = 'block';
    if (!attributes.nopopup) {
      if (attributes.loadmsg) {
        Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
        attributes.loadmsg = null;
      }
    }
    $.ajax(attributes);
  }
}

i have try to convert the above code like this

XMLRequestDefaultHandler = function() {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open('GET', 'index.php/request', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {

    } else {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');


    }
  };
  xmlHttp.send(null);

}

8
  • why do you even want to? Commented Oct 18, 2015 at 9:52
  • 4
    Read up on XMLHttpRequest: MDN, spec. Commented Oct 18, 2015 at 9:53
  • Also read about jqueery AJAX - api.jquery.com/jquery.ajax - understand that and the previous link, and you'll be on your way very quickly Commented Oct 18, 2015 at 9:55
  • i have try to change but not working Commented Oct 18, 2015 at 10:01
  • i want that some one help me to convert this to native js Commented Oct 18, 2015 at 10:02

1 Answer 1

12

I extracted ajax function of Jquery, to work without jquery.

And replace $.ajax(attributes); to ajax(attributes);

JQuery's ajax function, without JQuery :

function ajax(option) { // $.ajax(...) without jquery.
    if (typeof(option.url) == "undefined") {
        try {
            option.url = location.href;
        } catch(e) {
            var ajaxLocation;
            ajaxLocation = document.createElement("a");
            ajaxLocation.href = "";
            option.url = ajaxLocation.href;
        }
    }
    if (typeof(option.type) == "undefined") {
        option.type = "GET";
    }
    if (typeof(option.data) == "undefined") {
        option.data = null;
    } else {
        var data = "";
        for (var x in option.data) {
            if (data != "") {
                data += "&";
            }
            data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
        };
        option.data = data;
    }
    if (typeof(option.statusCode) == "undefined") { // 4
        option.statusCode = {};
    }
    if (typeof(option.beforeSend) == "undefined") { // 1
        option.beforeSend = function () {};
    }
    if (typeof(option.success) == "undefined") { // 4 et sans erreur
        option.success = function () {};
    }
    if (typeof(option.error) == "undefined") { // 4 et avec erreur
        option.error = function () {};
    }
    if (typeof(option.complete) == "undefined") { // 4
        option.complete = function () {};
    }
    typeof(option.statusCode["404"]);

    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
        else { xhr = new XMLHttpRequest(); }
    } else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 1) {
            option.beforeSend();
        }
        if (xhr.readyState == 4) {
            option.complete(xhr, xhr.status);
            if (xhr.status == 200 || xhr.status == 0) {
                option.success(xhr.responseText);
            } else {
                option.error(xhr.status);
                if (typeof(option.statusCode[xhr.status]) != "undefined") {
                    option.statusCode[xhr.status]();
                }
            }
        }
    };

    if (option.type == "POST") {
        xhr.open(option.type, option.url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.send(option.data);
    } else {
        xhr.open(option.type, option.url+option.data, true);
        xhr.send(null);
    }

}
Sign up to request clarification or add additional context in comments.

5 Comments

this is working fine when i send 'GET' and 'POST' request please update how i will send the query string to 'GET' method
Set data of attributes object like this : data: { string: "My string" },
Doesn't work with JSON payloads because of the fixed content-type.
I'd remove || xhr.status ==0 from the success function as that's the default status, the status returned on a timeout, the error status for some browsers. Add something like this: xhr.ontimeout = function(){}; instead. link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.