javascript tutorial - [Solved-5 Solutions] Make an AJAX call without jQuery - javascript - java script - javascript array



Problem:

How to make an AJAX call using JavaScript, without using jQuery ?

Solution 1:

With "vanilla" JavaScript:

<script type="text/javascript">
function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</script>
click below button to copy the code. By JavaScript tutorial team

With jQuery:

$.ajax({
    url: "test.html",
    context: document.body,
    success: function(){
      $(this).addClass("done");
    }
});
click below button to copy the code. By JavaScript tutorial team

Solution 2:

We can use the following function:

function callAjax(url, callback){
    var xmlhttp;
    // compatible with IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

We know this is a fairly old question, but there is now a nicer APWE available natively in newer browsers. The fetch() method allow we to make web requests. For example, to request some json from /get-data:

var opts = {
  method: 'GET',
  body: 'json',
  headers: {}
};
fetch('/get-data', opts).then(function (response) {
  return response.json();
})
.then(function (body) {
  //doSomething with body;
});
click below button to copy the code. By JavaScript tutorial team

Solution 4:

	var xhReq = new XMLHttpRequest();
 xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", false);
 xhReq.send(null);
 var serverResponse = xhReq.responseText;
 alert(serverResponse); // Shows "15"
click below button to copy the code. By JavaScript tutorial team

Solution 5:

This may help:

function doAjax(url, callback) {
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}


click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Make an AJAX call without jQuery