javascript ajax get code example

Example 1: jquery ajax get

$.ajax({
    	url: "www.site.com/page",
    	success: function(data){ 
    	    $('#data').text(data);
    	},
    	error: function(){
    		alert("There was an error.");
    	}
    });

Example 2: ajax data post call in javascript

$.ajax({
   url: 'ajaxfile.php',
   type: 'post',
   data: {name:'yogesh',salary: 35000,email: '[email protected]'},
   success: function(response){

   }
});

Example 3: ajax get js

let xhr = new XMLHttpRequest();

xhr.open("GET", "une/url");

xhr.responseType = "json";

xhr.send();

xhr.onload = function(){
    if (xhr.status != 200){ 
        alert("Erreur " + xhr.status + " : " + xhr.statusText);
    }else{ 
        alert(xhr.response.length + " octets  téléchargés\n" + JSON.stringify(xhr.response));
    }
};

xhr.onerror = function(){
    alert("La requête a échoué");
};

xhr.onprogress = function(event){
    if (event.lengthComputable){
        alert(event.loaded + " octets reçus sur un total de " + event.total);
    }
};

Example 4: how to make ajax request javascript

//Change the text of a <div> element using an AJAX //request:
//using JQuery


$("button").click(function(){
  $.ajax({url: "demo_test.txt", success: function(result){
    $("#div1").html(result);
  }});
});



//To send a request to a server, we use the open() //and send() methods of the XMLHttpRequest object:
// Javascript


xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

//example below
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>


<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "demo_get.asp", true);
  xhttp.send();
}
</script>

</body>
</html>

Example 5: js ajax receive html

$.ajax({
  	type: 'POST',
  	url: "<Your URL>",
	contentType: 'application/json; charset=utf-8'
  	// Set your dataType to either 'html' or 'text'.
	// Keep in mind: dataType is for receiving,
	// contentType is for sending
  	dataType: 'html',
  	data: { example: 1, id: "0x100"},
	// Note: the data above is used in sending,
	// data below is a variables that stores received data
  	success: function (data){
     	// Suppose you have an html element, where you want to append 
     	// the response:
     	$('#<Your html element id>').html(data);
  		// .html(data) overwrites existing data
		// Use .append(data) to add response without overwriting!
  	}
});