How to use the combination: JQuery + Ajax + PHP + JSON

September 26th, 2010  | Tags: , , , ,

After a long time, I have decided to write a simple but useful post for whom is working in a WEB 2 application using PHP as script language.
Certainly you have already heard about JQuery. In this topic we’re going to show up how to use AJAX with PHP. Furthermore, we’re going to show up an example using JQuery + AJAX + PHP + JSON.

First Example – JQuery + AJAX + PHP

In the first example, we’re going to create a simple page (index.php) with a single text field and a button. When the user clicks on the button, an ajax call will be fired.
The content of the text field will be sent out to a PHP file (ajaxExample.php) and it will return the content in uppercase. Finally, the new content will be displayed in the first page (index.php).
All of those actions are going to be performed in an AJAX way. Hands on.

index.php

As said, there will be a text field and a button in the index.php. Check it out the code below:

<html>
<head>
	<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
	<h2>JQuery + AJAX + PHP - First Example</h2>
	<form>
		Name: <input type="text" name="name" id="name" /><br />
		<input type="button" id="button" value="Click me" />	
	</form>
        <div id="loading">Loading...</div>
	<div id="result" />
</body>
</html>

Nothing special on the code above. On line 3 we have added the JQuery file. Also, we have the form with the text field and the button and two DIVs: one to show the loading string and the other one to show the result. Now, go to the next step.

ajaxExample.php

This is the simplest file. Basically it gets the value from the name attribute, wait for 2 seconds and return the name in uppercase mode.

<?php
$name = $_POST['name'];
sleep(2);
echo strtoupper($name);
?>

JQuery and AJAX Code

Finally, let’s the see cool part, where the JQuery call the ajax function. Let’s see the code:

	$(function() {
		$("#loading").hide();
		$("#button").click(function() {
			$.ajax({
				type: 'POST',
				data: 'name=' + $("#name").val() ,
				url: 'ajaxExample.php',
				success: function(data) {
					$("#loading").hide();
					$("#result").text(data);
				},
				beforeSend: function() {
					$("#loading").show();
				}
			});		
		});
	});

The code above makes the ajax call. As you can see, the code is straightforward, but If you need more information about the parameters, please check the JQuery AJAX API.
Now, run the application and you’re gonna see how the code works.

If you prefer, you can download the example above here.

JSON

If you’re not familiar with JSON, please check this site out.
JQuery handles JSON usando the JSON.parse method. In the PHP side, there are two methods: encode_json and decode_json. Let’s see another example:

index.php

<html>
<head>
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript">
		$(function() {
			$("#result").hide();
			$("#json_anchor").click(function() {				
				json_call();
			});
		});	
 
		function json_call() {
			$.ajax({
				type: 'POST',
				url: 'json.php',
				success: function(data) {										
					var myObject = JSON.parse(data);
					$("#name").text(myObject.name);
					$("#age").text(myObject.age);			
					$("#result").show();		
				}
			});
		}
	</script>
</head>
<body>
	<h2>Hello JSON + PHP World</h2>
	<a href="#" id="json_anchor">Click here</a>
	<div id="result">
		<table border="0">
			<tr>
				<td width="50px"><strong>Name</strong></td>
				<td id="name"></td>		
			</tr>
			<tr>
				<td><strong>Age</strong></td>
				<td id="age"></td>		
			</tr>
		</table>
	</div>
</body>
</html>

json.php

<?php
	require_once('Customer.class.php');
	$customer = new Customer('Jair',28);
	echo json_encode($customer);
?>

See above, we’re using the json_encode method to transform an object (Customer) into a JSON object.

Customer.class.php

<?php
class Customer {
 
	public $name;
	public $age;
 
	function __construct($name, $age) {
		$this->name = $name;
		$this->age	= $age;
	}
}
?>

Running the example you’re gonna see a link. When the user clicks on the Link a table with the name and age will be displayed. This call is made by AJAX.
You can download this example here.

As you can see, use JQuery is useful for AJAX call. The biggest advance of JQuery, is that you can use JQuery with almost any language: PHP, Ruby, Java and so on. I hope this topic be useful for anyone.
If you have any question or comment, fell free to let your message below

No comments yet.

TOP