How to use ajax

first why ?
The simplest explanation is for update part of your page with data that come from your server without refresh the page and Asynchronous.

Let’s say we have two files
1 index.html that call to the second file and brings random number, and 2 random.php that return random number

There are two possibilities to implement this :
1)the two file together on the same server, and then we don’t have problem just call to random like this“GET”, “random.php”, true);

2)Let’s say you have application on your smartphone that have the index.html and in the remote server the random.php, meaning not on the same server.
the call to the server will be like this"GET", "", true);

But now we need to add another line in the random.php that allows access from another server, like this

header("Access-Control-Allow-Origin: http://localhost:1337");

The full example :

<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <title>First ajax</title>
        var xmlHttp;

        function getNum()
            xmlHttp = new XMLHttpRequest();
            //set listener, it's mean when the state is change we call the callback function in the right
            xmlHttp.onreadystatechange = callback;
            //open connection to the server, true mean the call will be Asynchronous
  "GET", "", true);
            //we send empty data to the server so we can begin the conversation with the server and wait for data comes back

        //when information comes back from the server: ready state,status
        function callback()
            //we check how many times the callback function run
            console.log("readyState : "   xmlHttp.readyState   "\nstatus : "   xmlHttp.status);
            //4 mean the request is finish and the response is ready,status 200 mean the response is ok
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                document.getElementById('result').innerHTML = xmlHttp.responseText;
    <div id="result">

    <input type="button" value="get random number" onclick="getNum();">



header("Access-Control-Allow-Origin: http://localhost:1337");
This entry was posted in כללי and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s