Sunday, 19 October 2014

Example AJAX with JSON, jQuery, PHP and MySQL

In the index.php file I connect to the database and I load the name of the products, one for each div. Each div has an id which is the id of the product (also retrieved from the database) and a class: name_product
I also built a second div which will load product data. This second div will have an id: “data” + id of the product and a class: data_product
Step 3 – code.js
$(document).ready(function() {
//Tutorial - www.Ajax101.com

$('.name_product').click(function() {
//we get the id of the selected product
var id = this.getAttribute('id');
//we create the object with the product id
var data = {
idProduct : id
}
//we get the selected div
var div = $('#' + id);
//if the div does not have the class "loaded", we make ajax request
if (!div.hasClass("loaded")) {
$.ajax({
data : data,
url : 'data.php',
global : false,
type : "GET",
dataType : "html",
async : false
}).done(function(result) {
//decode the JSON object received
var data_product = JSON.parse(result);
//we select the div to load the data of the selected product
var datadiv = document.getElementById('data' + data_product[0].id);
datadiv.innerHTML = "";
datadiv.innerHTML += "Description: " + data_product[0].description;
datadiv.innerHTML += "<br>Price: " + data_product[0].price + " €<br/>";
});
}
//we add the class loaded
div.addClass("loaded");
});
});

data.js file will run each time that we select a product. It will make an AJAX request to data.php by passing the id of the selected product. In the second div, paint the data received from data.php
Step 4 – data.php
<?php
$con = mysql_connect("localhost", "root", "root");

if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("shop", $con);
$id=$_GET["idProduct"];
$result=mysql_query("SELECT * FROM products WHERE id='$id'");
$productArray = array();
while ($products=mysql_fetch_assoc($result)) {
$productArray[] = array_map('utf8_encode', $products);
}
//we send the array as JSON object
echo json_encode($productArray);
?>

File “data.php” receive the data object with the attribute idProduct. We connect to the database and select the product that has that id
https://asmclk.com/click.php?aff=105539&camp=148257&sub1=