2009
08.22

Usually, i write software in ASP.NET/C#, because this is what my job requires, however i always lilke to play with other technology to keep myself up-to-date. I’ve been writing alot of Ajax enabled websites in ASP.NET recently, and have to say Microsoft have made it very easy to integrate with an ASP.NET Aplpication. It got me wondering how difficult would it be with PHP? Surely just as easy?

Well, there isn’t much in it. And it didn’t take me long at all to get a simple AJAX POST running on a PHP Page, which returned me some data that i would be able to re-use.

I will assume you have a PHP (5.2) enabled apache server that you have access to dump a couple of files that we are going to want to use. Fire up your favourite PHP Editor (I use Eclipse PDT).

Lets start by creating an index.php, which will initiate our call to the backend. It should look similar to this…

<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
	<script type="text/javascript">
		function runPost()
		{
			$.post('service.php',
			   {
				   data: 2
  			   },
			   function(response, status)
			   {
				   alert(status);
				   for ( var i = 0; i < response.length; i ++)
	    				alert(response[i].Data);
			   },	
			   'json');
		}
	</script>
	This is our test page.<br />
	<button id="testButton" onclick="runPost();">Make Ajax Post</button>
</body>
</html>

As you can see, a pretty simple page, with an external link to the wonderful google which’ll host jQuery for us (saves us hosting it, users can download it faster). We also have a simple method which uses the jQuery post method. This is what we will be using to talk to our web service. Let’s have a quick look at the post method. It takes upto 4 parameters, all of which we are interested in.

First up, we have the URL we want to post to (this is our web service!), we then have the data we want to send to the server. There is some magic going on here, because we can just throw an Javascript Object at it, it will then serializa that into a JSON formatted string, which PHP will understand. Then we have a callback, this is the method that will be called when the request has finished, succesful or not. Last but not least, we have the data type, for this example we use JSON, because that’s the data we want to send/receive. That’s it, it’s a simple method that does everything we want to do! So let’s create our service page.

Create another page called service.php in the same folder as the index.php file, for simplicity.

<?php
 
	class data
	{
		public $Index;
		public $Data;
	};
 
	$myObj = json_decode(stripslashes($_POST['data']));
	$returnObj = array();
 
	for ($i = 0; $i < $myObj; $i ++)
	{
		$newData = new data();
		$newData->Index = $i;
		$newData->Data = 'This is a Test, ' . $i . '.';
		$returnObj[] = $newData;
	}
 
	echo json_encode($returnObj);
 
?>

As you can see, we take the POST’ed data argument, and transform it into the integer that we actually passed, then loop through the amount that it is equal to, creating an array that we want to serialize to json and send back to the client! Simples!

If you now run the index page in your favourite browser (Should be FireFox!) then click the button, you should get 3 message boxes pop up.

The first should say Success, then we should get ‘This is a test, 0.’ and ‘This is a test, 1.’. And that’s it, that is just how easy it is to post data to the server and deal with a response using jQuery & PHP. Try changing the data parameter we pass back in the runPost() JavaScript method in index.php to see how it varies.

A plugin i highly suggest for FireFox is FireBug, this will allow you to view all the POST’s and the Responses in a nice little window, so you can ensure that data you are sending/receiving is exactly as you want to see.

I hope this helped someone!

1 comment so far

Add Your Comment
  1. It helped me… a lot!
    Thanx!

Spiked Software Coding Articles is Digg proof thanks to caching by WP Super Cache