Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I re-write this code without jQuery?

How can I rewrite this code without using jQuery? I need to do it in a mobile app where I can't use jQuery.

 $.ajax({
            type: "POST", 
            url:"../REST/session.aspx?_method=put",
            data: JSON.stringify(dataObject, null,4),
            cache: false,
            dataType: "json",
            success: onSuccessLogin,
            error: function (xhr, ajaxOptions){
                    alert(xhr.status + " : " + xhr.statusText);
                }    

        }); 
like image 500
selladurai Avatar asked Mar 14 '26 14:03

selladurai


1 Answers

You can try this:

var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
    // What you want to do on failure
    alert(xmlhttp.status + " : " + xmlhttp.responseText);
  }
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    // What you want to do on success
    onSuccessLogin();
  }
}

xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));

As for how to do more stuff with only javascript without jQuery library take a look at W3Schools AJAX Tutorial or Mozilla - Using XMLHttpRequest

And as duri said, you will have to find a way to convert dataObject to string, as not all browsers support JSON object.

like image 180
enoyhs Avatar answered Mar 16 '26 04:03

enoyhs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!