Web Info and IT Lessons Blog...

Friday 10 April 2015

Ajax Request to server using javascript

The previous lesson of Javacript Lessons Series was about setInterval method and in this lesson we will learn to make AJAX requests in javascript.

Ajax Request using javascript

The word AJAX stands for asynchronous Javascript and XML. AJAX request is used to fetch data from server on javascript events without reloading the page. There are two types of AJAX requests i.e

1. GET Request
2. POST Request

Comparison of GET and POST Requests:

GET request is more simpler and faster than POST request. However it should not be used where we want to send large amount of data to the server or where we want to send the user input to the server as POST is more secure than GET.

AJAX Request using GET Method:

A simplest AJAX request would be calling a PHP file on javascript click event and alert the response of PHP file without refreshing the page. Let us say we have a PHP file (index.php) containing the code given below:

PHP Code:


<?php 
echo 'Hello from PHP!';
?>

Now let us create an Html button and attach onclick event to it using javascript.

HTML Code:


<input type="button" id="btn1" value="Ajax Call" />

When the above button is clicked, we will call a javascript function to make an ajax request to the PHP file (index.php) and alert the response of the PHP file in javascript. Javascript code of attaching event to the button and making an ajax call using get method is given below:

Javascript Code:


<script type="text/javascript">
var btn1 = document.getElementById('btn1');
btn1.onclick = ajaxCall;

function ajaxCall(){
 var xmlhttp;
 if (window.XMLHttpRequest)
 {
   xmlhttp=new XMLHttpRequest();
 }
 else
 {// This code is for lower browsers like IE5,IE6
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function()
 {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {// Alert the response from PHP file
  alert(xmlhttp.responseText);
   }
 }
 // Open PHP file using get method 
       (the third parameter true means asynchronous method) 
 xmlhttp.open("GET","index.php",true);
 // Send request to server
 xmlhttp.send();
}
</script>

In the above example we have not sent any information to the PHP file using GET method. If we want to send some user information in the AJAX request to the server we can send it in the url of the request. Let us look at another example in which the user will input his name in the html text field and then we will send the name in the AJAX request to the server. The response of server will depend upon the name received in the request. In html part we would only need an html text field and a button i.e

HTML Code:


<input type="text" id="name" />
<input type="button" id="btn1" value="Ajax Call" />

We will also change the PHP code a bit. If we receive name in the GET array and the name is 'John', the response of PHP file will be 'You are John!' else 'You are not John!'.

PHP Code:


<?php 
if(isset($_GET['name'])){
 $name = $_GET['name'];
 if($name == 'John'){
  echo 'You are John!';
 }else{
  echo 'You are not John!';
 }
}
?>

In the above PHP code we have used If/Else statements to decide the response of PHP file based upon the name filled in the html text field. Now we will do some minor changes in the previous javascript code to send the name of user in the Ajax request. New javascript code is given below:

Javascript Code:


<script type="text/javascript">
var btn1 = document.getElementById('btn1');
btn1.onclick = ajaxCall;

function ajaxCall(){
 var xmlhttp;
 // Get the name entered in the text field
 var name = document.getElementById('name').value;
 if (window.XMLHttpRequest)
 {
   xmlhttp=new XMLHttpRequest();
 }
 else
 {// This code is for lower browsers like IE5,IE6
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function()
 {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {// Alert the response from PHP file
  alert(xmlhttp.responseText);
   }
 }
 // Open PHP file using get method and send the 
        parameter name in the url 
 xmlhttp.open("GET","index.php?name="+name,true);
 // Send request to server
 xmlhttp.send();
}
</script> 

AJAX Request using POST Method:

Ajax Post request is similar to Get request with little changes. If we want to send data to the server in Post request, we cannot do it in the url like we used to do in Get request and to Post data we have to set setRequestHeader(). These are the only changes we need to do in the Post request.

If we want to make an ajax call to a php file (index.php) and send name of the user, all we have to change in the above AJAX Get Request are these lines:


xmlhttp.open("POST","index.php",true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send("name="+name);

and off course we need to change our PHP file a bit. Now we will check the POST array and decide the response of the server.

For more lessons on Javascript subscribe on InformationBitz.com

No comments:

Post a Comment