In this tutorial you will learn about the AJAX Request and its application with practical example.
After checking the browser support or successfully creating the XMLHttpRequest object, we can exchange the information between server and webpage by making the request using XMLHttpRequest object.
XMLHttpRequest object have the following methods to send a request to server –
Method | Description |
---|---|
open(method,url,async) | We can now open our request to the server by calling the open method that belongs to the AJAX object that we created in previous chapter.This method takes three parameters.
method: The method parameter can have a value of “GET” or “POST”. url: Location of the script on the server async: TRUE or FALSE(Asynchronous means that the processing will continue on without waiting for the server side retrieval to complete whereas a synchronous call would stop all other processing and wait for the response from the server) |
send(string) | Sends the request to the server.string: Only used for POST requests |
setRequestHeader(header,value) | Adds a header/value pair to the HTTP header to be sent.
header:Header name value: Header value |
1 2 3 4 5 6 |
<script language="javascript"> xmlhttp.open("GET","result.php",true); xmlhttp.send(); document.getElementById("result_div").innerHTML=xmlhttp.responseText; </script> |
1 2 3 4 5 6 7 8 |
<script language="javascript"> /* To avoid the cached result we can add a random string to the URL */ xmlhttp.open("GET","result.php?r=" + Math.random(),true); xmlhttp.send(); document.getElementById("result_div").innerHTML=xmlhttp.responseText; </script> |
1 2 3 4 5 6 7 8 9 |
<script language="javascript"> /* To POST form data ,sets HTTP header with setRequestHeader(). Specify the data you want to send in the send() method */ xmlhttp.open("POST","post_form.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("name=christene&roll=101"); </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<script language="javascript"> <!-- var xmlhttp; function createObject(){ try{ // Opera 8.0+, Firefox, Safari xmlhttp= new XMLHttpRequest(); }catch (e){ // Internet Explorer Browsers try{ xmlhttp= new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("Browser not supports AJAX!"); return false; } } } } //--> xmlhttp=createObject(); xmlhttp.open("GET","result.php",true); xmlhttp.send(); document.getElementById("result_div").innerHTML=xmlhttp.responseText; </script> |