This project will demonstrate how to use Ajax in PHP and JQuery
- CRUDPHPwithPDO
- index.php
- product.php
- ajax1.php
- ajax2.php
- ajax3.php
- ajax4.php
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button1').click(function(){
$.ajax({
type:'POST',
url:'ajax1.php',
success:function(result){
$('#result').html(result);
}
});
});
$('#button2').click(function(){
$.ajax({
type:'POST',
data:{a:1,b:2},
url:'ajax2.php',
success:function(result){
$('#result').html(result);
}
});
});
$('#button3').click(function(){
$.ajax({
type:'POST',
url:'ajax3.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:'ajax4.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="Product Info" id="button3">
<input type="button" value="Product List" id="button4">
<br>
<div id="result"></div>
</form>
<?php
class Product{
var $id;
var $name;
var $price;
}
?>
<?php
echo 'Hello World';
?>
<?php
echo $_POST['a'] + $_POST['b'];
?>
<?php
require 'product.php';
$product = new Product();
$product->id = 'p1';
$product->name = 'Product 1';
$product->price = 100;
echo json_encode($product);
?>
<?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);
?>
Screenshots
Demo 1
Demo 2
Demo 3
Demo 4