Ajax with PHP


Creates new PHP file named product.php. This file contains product description information

<?php
class Product{
	var $id;
	var $name;
	var $price;
}
?>

Creates new PHP file named hello.php. This file displays a string as below:

<?php
	echo 'Hello World';
?>




Create new PHP file named sum.php. This file performs a two-digit sum from the parameter

<?php
	echo $_POST['a'] + $_POST['b'];
?>

Create new PHP file named json.php. This file that converts the product object to a json string

<?php
require 'product.php';
$product = new Product();
$product->id = 'p1';
$product->name = 'Product 1';
$product->price = 100;
echo json_encode($product);
?>

Create new PHP file named listjson.php. This file that converts the product array to json string

<?php
require 'product.php';
$listProducts = array();

$product1 = new Product();
$product1->id = 'p1';
$product1->name = 'Product 1';
$product1->price = 100;
array_push($listProducts, $product1);

$product2 = new Product();
$product2->id = 'p2';
$product2->name = 'Product 2';
$product2->price = 200;
array_push($listProducts, $product2);

$product3 = new Product();
$product3->id = 'p3';
$product3->name = 'Product 3';
$product3->price = 300;
array_push($listProducts, $product3);

echo json_encode($listProducts);
?>




Create new PHP file named index.php. This page contains buttons that will call json from the files above

<script src="js/jquery-1.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
	$('#button1').click(function(){
		$.ajax({
			type:'POST',
			url:'hello.php',
			success:function(result){
				$('#result').html(result);
			}
		});
	});

	$('#button2').click(function(){
		$.ajax({
			type:'POST',
			data:{a:1,b:2},
			url:'sum.php',
			success:function(result){
				$('#result').html(result);
			}
		});
	});

	$('#button3').click(function(){
		$.ajax({
			type:'POST',
			url:'json.php',
			success:function(result){
				var product = $.parseJSON(result);
				var s = 'Id: ' + product.id;
				s += '<br>Name: ' + product.name;
				s += '<br>Price: ' + product.price;
				$('#result').html(s);
			}
		});
	});

	$('#button4').click(function(){
		$.ajax({
			type:'POST',
			url:'listjson.php',
			success:function(result){
				var listProducts = $.parseJSON(result);
				var s = '';
				for(var i=0; i<listProducts.length; i++){
					s += '<br>Id: ' + listProducts[i].id;
					s += '<br>Name: ' + listProducts[i].name;
					s += '<br>Price: ' + listProducts[i].price;
					s += '<br>===============';
				}
				$('#result').html(s);
			}
		});
	});

});
</script>
<form>
<input type="button" value="Hello" id="button1">
<input type="button" value="Sum" id="button2">
<input type="button" value="Json" id="button3">
<input type="button" value="List Object with Json" id="button4">
<br>
<div id="result"></div>
</form>




Demo 1

Demo 2

Demo 3

Demo 4

I recommend you refer to the books below to learn more about the knowledge in this article: