Simple AJAX - PHP and Javascript

Skill

Simple AJAX - PHP and Javascript

Posted in:

So, we now have a pretty common appearance of Web 2.0 across the world, but what exactly is Web 2.0? Really there are not set definitions or rules behind Web 2.0, it is just a way of describing a new set of technologies that have recreated the web. One of the more exciting and cool technologies is asynchronous server communication, sometimes referred as AJAX. With AJAX you don't need to refresh a page to get information from the server. You can call server pages and get the response, all with Javascript. In this tutorial I will show you the most basic way to get a response from a PHP script.

This tutorial will cover just the basics with AJAX, and we will start with the base object you need: a XMLHTTP Javascript object. With this object you call a server-side script and get the response back. Most browsers use the same Javascript object, but of course Microsoft has to be different, so they require their own. The following function will return the correct object:

function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}

This code will, again, return an XMLHTTP object to use in our Javascript. What is going to happen is that we are going to use this object to make an HTTP request through Javascript. When we get a response back, we will simply place it in the page, nothing fancy. In order to make the request we use the following code:

function MakeRequest()
{
  var xmlHttp = getXMLHttp();
 
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      HandleResponse(xmlHttp.responseText);
    }
  }

  xmlHttp.open("GET", "ajax.php", true);
  xmlHttp.send(null);
}

The key to this whole process is using the XMLHTTP member readyState, which is pretty much exactly what it sounds like. The readyState corresponds to the state of the object itself, which can be anything from Uninitialized to Loaded. In the case of an AJAX request, we wait for the readyState to be 4, which is the maximum value and tells us that all the data to be loaded from the request is. So when the readyState is 4, the request is done and the data is ready for display.

Once you take care of catching the readyState, you need to make the actual request, using the open() and send() methods. The open method is what we use to set up the request. It takes in a request type (ie "post" or "get"), the page URL, and a boolean value indicating wheather we are making an asynchronous call or not. In this case we are, so it is true. So to set up the open() call, we use GET, ajax.php for the url, and set the asynchronous boolean to true.

After you have your open() method all set up, you need to call send() to make the actual request. The send() method makes the request, sending all the arguments you give it. For this case, we are sending nothing, so the arguments are null. When we get the response back, we have to do something with the data sent back. We use the HandleResponse() function to display the information sent back, when the readyState is 4 of course. The HandleResponse() function look like so:

function HandleResponse(response)
{
  document.getElementById('ResponseDiv').innerHTML = response;
}

All this function does is take the response from the request and puts it in a div on our page. Now, that is all our Javascript, which works just fine all in one file, which we will call ajax.js. Now that we have our Javascript, we need to make our ajax.php file, with is one monsterous file, full of complex code:

<?php
echo "This is a php response to your request!!!!!!";
?>

Yep, that is it. One echo statement is all we really need for this tutorial. The concept is that all we need to do is send something back to the XMLHTTP object. In the simplest form, this is just some text, where PHP's echo statement works perfectly. This will return our statement back and Javascript will display it on the page. But what about the page eh?

The page in question can really be anything as long as it calls the MakeRequest() method in our javascript file. In our case we will make a simple index.html page that will have a button and a div. The code will look something like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <script type='text/javascript' src='ajax.js'></script>
    <title>PHP AJAX Example</title>
  </head>
  <body>
    <input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
    <div id='ResponseDiv'>
      This is a div to hold the response.
    </div>
  </body>
</html>

The HTML itself is very simple and easy to understand, and this page is less than basic. All it has is a button that calls our MakeRequest() method and the Response div that holds the response. To give you a better example :

This is a div WITHOUT anything important in it

As you can see, the page did not refresh, yet we got our echo from the php script. Asynchronous communications are so wondrous, aren't they? Now all you have to do is fill in the PHP file with something a little more useful. Some of the more complex stuff includes sending whole objects to Javascript, but that is for another time. For now, this tutorial is all wrapped up. Just Remember that whenever you need coding help, just switch on the code ;)

Outsourcing Company
06/04/2008 - 10:47

Really good work. I found a lot of profound information which can help me to go on.

reply

Thiago
06/09/2008 - 12:52

Hi. There is a post on Ajaxian which says we should limit the try/catch statements on our JS. I know this is just a dummie sample and it wont make a lot of different, but, maybe it would be nicier to use a simple if instead of try/catch for an application that does a lot of requests, having to create several instances of XmlHttpRequest object. I use something like this:

function getXHRObject() {
    var xmlObj;
    if('Microsoft Internet Explorer' == window.navigator.appName) {
        xmlObj = new ActiveXObject("Microsoft.XMLDOM");
    } else {  
        // other browsers        
        xmlObj = new XMLHttpRequest();
    }
    xmlObj.async="false";
    return xmlObj;
};

reply

vijay
03/28/2009 - 02:10

hey this is not working in IE 6 :(

reply

good
02/07/2011 - 01:21

good

reply

sri
06/29/2011 - 04:30

use this in ur else part
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

reply

fariq
04/14/2009 - 04:13

change ("Microsoft.XMLDOM") to ("Microsoft.XMLHTTP") to make it works..tested in IE6

reply

Denis Mazourick
06/11/2008 - 05:23

Good post. Thank you. But why just not use the MS AJAX components? There're 3 JS files that need to be included into the page and you have pretty well designed, cross-platform AJAX engine. I was successfully used it in projects written in PHP and other languages, hosted on Apache.

reply

Fnfzone
06/30/2008 - 11:59

Nice info

thanks

reply

Janus
07/01/2008 - 06:43

This is great! I haven't seen something so simple and so easy to understand as yours in the recent past.

reply

Moo
07/16/2008 - 19:40

Nice and simple for conceptual purposes, and I like that you had the server send back a response, unlike this tutorial: http://www.ajaxf1.com/tutorial/ajax-php.html

But how about something useful, like where the server tries to return a php array? You said another time, now do it! ;P

reply

Karlis_I
08/26/2008 - 15:39

Nice.
Thanks!

reply

Randy K
08/29/2008 - 10:36

Thanks for writing a easy but in some ways comprehensive example.

Best Regards,
Randy

reply

Assbear
08/29/2008 - 18:30

This is amazing info! I set up a page testing this in five minutes, and it worked -
Plus I spiced it up by returning data from a mysql db on the onClick - which I thought was impossible, but is wasn't, and it's really really awesome.
Thanks a lot!

reply

Samy
09/24/2008 - 01:07

AJAX Really made simple.
Lot simpler than lot of frameworks. Thanks A Lot.

reply

Upul Suresh
10/01/2008 - 23:11

php ajax learn

reply

Sam
10/03/2008 - 12:25

Great Job !!

reply

Anonymous
10/07/2008 - 21:52

GREAT!!!!!

reply

Ff
11/17/2008 - 09:00

gooooood

reply

Web designer Kathaperumal
11/26/2008 - 05:17

This is really very good article on AJAX. useful and elementary but powerful

reply

Stu
11/28/2008 - 12:14

Great, Simple yet very effective, just built a small calculator using it.

reply

Christopher Shennan
12/09/2008 - 03:52

I been meaning to look into AJAX a while ago and if I knew it was as easy at that I would have actually done it long before now.

Congratulations on a very novice friendly article!

reply

Anonymous
12/14/2008 - 20:30

Terrific!!

reply

John Secanth
12/15/2008 - 10:32

Another interesting approach of integrating PHP and AJAX:

http://lionframework.blogspot.com/2008/12/ajax-was-never-easier.html

reply

samuel
03/28/2009 - 01:42

hey this blog is not found :(

reply

Anonymous
09/01/2009 - 17:48

it's at http://www.lionframework.org/blog/2009/02/ajax-was-never-easier/

reply

Defmer
12/22/2008 - 18:17

awesome, simple and to the point.

reply

Shiji
12/24/2008 - 00:27

Really good and very helpfull
thanks

reply

Chris Zahrt
06/17/2009 - 13:29

You may need to change line:

xmlHttp.open("GET", "ajax.php", true);

to:

xmlHttp.open("GET", "ajax.php" + Math.random(), true);

in order to get it to load from the server every time instead of cache. Only needed if the content of the responce changes with each request.

reply

Chris Zahrt
06/17/2009 - 13:30

Correction:
xmlHttp.open("GET", "ajax.php?" + Math.random(), true);

Note the "?"

reply

The Fattest
06/17/2009 - 15:54

Good point, that is one way to handle it. I think setting the http header cache-control to no-cache would also work.

reply

Anonymous
06/21/2011 - 07:19

explain......all

reply

iNishana
07/15/2009 - 03:29

Hi.

Thanks for the article.

Nice and simple, But I keep getting this error:

Error: no element found
Line: 4, Column: 3
Source Code:
?>

I have also made the ajax.php file to be:

<?php header("Content-Type: plain/text");
echo "This is a php response to your request!!!!!!";
?>

any thoughts?

Thanks

reply

Rzabka
12/08/2009 - 15:10

Did you ever find a solution? I'm having the same problem and cannot figure out what it is. I tried everything suggested on various forums.

reply

biiim
05/23/2011 - 09:27

Hi,

old i know but unanswered.

The error sounds like javascript can't find the element on the page, i dont see any of your code but its likely to be either:
you dont have a div on the page with an id of 'ResponseDiv' this is case sensitive

or you are calling the javascript before the div is on the page, try moving the script to just before the tag

Bim

reply

Bala
09/25/2009 - 02:32

Hi
when i click button, i called php file through ajax. In that php file i wrote like this

alert('sdf');

<?php
echo "This is a php response to your request!!!!!!";
?>

after getting response i load content into div element, now i get result only in the echo statement but not alert in the javascript.

Please help me!

reply

biiim
05/23/2011 - 09:31

Hi Bala,

sounds like you have put alert('sdf'); into your php file?

this won't run as javascript it will just return it as a string, you need to write into the onreadystatechange javascript function:

alert('sdf');

for it to be run as js

bim

reply

Tim
10/30/2009 - 11:36

Sweet! Simplest tutorial I have found.

reply

raj
01/06/2010 - 07:18

hi good article but some error

reply

Parvez
01/06/2010 - 07:21

Put Perfect Code Of AjAx

reply

Dash
01/27/2010 - 01:41

Nice & simple tutorial. Thanks

reply

Tat
02/02/2010 - 16:41

I tried your code. It works in same domain but not cross-domain. How can I make it works?

reply

karn
03/12/2010 - 00:22

Thanks for writing a easy but in some ways comprehensive example.

Best Regards,
karn

reply

Anonymous
04/25/2010 - 19:48

let try to be serious

reply

h
05/18/2010 - 00:28

hi , i tried tne above code in facebook app. but it dosent return echo statement?

reply

ajax.js
06/29/2010 - 02:47

ajax.js

pleas give me this file

reply

The Reddest
06/29/2010 - 08:49

The link to this file is at the bottom of the post, under Simple_Ajax_Example.js.

reply

M Hussain
07/09/2010 - 01:23

Nice and simple for conceptual purposes, and I like that you had the server send back a response, But how about something useful, like where the server tries to return a php array? You said another time, now do it! ;P

reply

ctky
09/23/2010 - 13:55

Check this out:

http://particletree.com/features/preloading-data-with-ajax-and-json/

if u haven't already....

reply

hai
11/13/2010 - 07:14

good

reply

Ryan
01/27/2011 - 17:00

I wonder should the php file store in the same folder on the server or could be anywhere.

reply

rj
03/08/2011 - 08:59

How to insert an array form using ajax?
the form done in javascript..TQ

reply

Ave
03/16/2011 - 09:09

if i want to call PHP file by using AJAX in function validate can or not.In my code for button submit i let onclick="return validate();" in function validate if all the fields are valid then it will update my sql table... But how im going to do??how to call my PHP file??

reply

biiim
05/23/2011 - 09:45

Hi Ave,

You would run your validate() function then in the section where all is validated and you would move on to submit the form call the ajax function instead but still return false

validate(){
if(){///check
}else{///check
}else{
//validated, submit form
submitForm();
}
return false;
}

function submitForm(){
value1 = document.getElementById('field1').value;
value2 = document.getElementById('field2').value;
var url = 'newbpmessage.php';
var vars = 'field1='+value1+'&field2='+value2;
updReq = getXMLHTTPRequest();
updReq.open('POST', url, true);
updReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
updReq.onreadystatechange = function() {//Call a function when the state changes.
        if(updReq.readyState == 4 && updReq.status == 200) {
alert(updReq.responseText);
}
}
updReq.send(vars);
}

i usually get my php script to return 'Y' on success then use an if(updReq.responseText == 'Y'){//do something}else{//do something else} so i can do things in javascript rather than just reply with text

reply

At
03/17/2011 - 03:59

How to pass data form form using AJAX to PHP file???

reply

Anonymous
04/12/2011 - 16:37

I'm not positive, but I think you would send it out with this line: xmlHttp.send(data to be sent here";

reply

biiim
05/23/2011 - 09:13

Hey At,

You put the ajax function into the onsubmit of your form eg

<form onSubmit='sendForm();return false;'>

and this ones a bit basic but your javascript would look something like this

function sendForm(){
        updReq = getXMLHTTPRequest();
        var value1 = document.getElementById('field1').value;
        var value2 = document.getElementById('field2').value;
        var url = 'ajaxUpdate.php';
        var vars = 'field1='+value1+'&field2='+value2;
        updReq.open('POST', url, true);
        updReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        updReq.onreadystatechange = function() {//Call a function when the state changes.
                if(updReq.readyState == 4 && updReq.status == 200) {
                        alert(updReq.responseText);
                }
        }
        updReq.send(vars);
}

function getXMLHTTPRequest() {
        var req =  false;
        try {
                /* for Firefox */
                req = new XMLHttpRequest();
        } catch (err) {
                try {
                        /* for some versions of IE */
                        req = new ActiveXObject(\"Msxml2.XMLHTTP\");
                } catch (err) {
                        try {
                                /* for some other versions of IE */
                                req = new ActiveXObject(\"Microsoft.XMLHTTP\");
                        } catch (err) {
                        req = false;
                        }
                }
        }
        return req;
}

you could run - onsubmit='sendForm(this);return false;' and then youd have the form object available to loop through if you have many fields to type out - the return false stops the browser actually submitting the form so it only runs the js

Bim

reply

Anonymous
04/13/2011 - 08:18

For Ajax..
what way i use, either this or jquery $.ajax(){....}
please specify..

reply

Italo André
08/08/2011 - 14:17

What a great work! This was written in 2008 but still being helpful.

I used this inside Magento ecommerce and it worked well. My first time using AJAX, this post was really useful and simple.

Thanks!

reply

Rahul Saini
01/31/2012 - 03:45

hi..

reply

Anonymous
08/12/2011 - 17:53

file 1.php

<body>
<?php echo '1111'; ?>
</body>

--------------
file 2.php
<body>
<?php echo '2222'; ?>
</body>

--------------
file 3.php
<body>
<script>
function Ajax(url,stdin,stdout) {
  var xmlHttpReq = false;
  var self = this;
  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (!self.xmlHttpReq) {
    alert('ERROR AJAX:( Cannot create an XMLHTTP instance');
    return false;
  }  
  self.xmlHttpReq.open('POST', url, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4 ) {
        document.getElementById(stdout).innerHTML=self.xmlHttpReq.responseText;
    }
  }
  self.xmlHttpReq.send(stdin);
}
Ajax('1.php','','a');
Ajax('2.php','','b');
</script>
<span id=a>aaaa</span><br><span id=b>bbbb</span>
</body>

-------------------------------
After calling 3.php, the result is:

aaaa
2222

Why?

reply

loki1511
10/24/2011 - 00:37

I have created a page and some links in the right side of the page.

The middle part of the page has a div called content

when i click the link in the right side the content div will get the respective content.

this works fine, but when i refresh the page by pressing F5 the current content is replaced to the first default content. how to stay on the current div content even after refresh.

reply

The Hairiest
10/24/2011 - 10:04

Hello Loki. What you are looking for is a session, which are used for keeping data in-between pages, and in turn also in-between page refreshing. Before you go PHP crazy though, I suggest reading up a bit on page life-cycles and considerations to take when using sessions. They can be a very complex beast and opens up a lot more security concerns and have the potential to become bloated very quickly.

All that being said, sessions are what you are looking for in this situation.

reply

loki1511
10/29/2011 - 04:17

Thanks for the reply. I have tried using the session its working fine for a single tab , but when u try to open two pages in multiple tab then this will not work.

Its better to use a javascript function which is called when the page is refreshed.

reply

bayuo
11/17/2011 - 09:40

This script is awesome. It helped me a lot. thanks for putting it up.

reply

Anonymous
01/10/2012 - 07:38

thanks

reply

vked
11/27/2011 - 00:39

nice tut sir!!!!!!!!!!!!1

reply

Abi
01/28/2012 - 11:51

I dont know why i dont get the alert,i copy pasted the same code inorder to see if it works..i am not getting any response from server..
I know there is something wrong with my configuaration,not sure what mistake i am making...
actually my .html runs with url
http://127.0.0.1:8020/Admin/admin.html

and my php is in location
http://localhost/workspace/Admin/serverscript.php
Dont know why it does not return any response...the code is yours which i copied and tried running..
Plzzzzzzzzzzzz helop

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.