Example AJAX with JSON, jQuery, PHP and MySQL






Today I will show you a simple example in which I use AJAX with JSON, jQuery, PHP and MySQL.

It’s a product list when you select one, it makes an ajax request to retrieve the data from a database and display them on screen.

example ajax jquery mysql

See live example clicking here

To create this example we will need: database, index.php, code.js and data.php

Step 1 – Create database

The first thing I do is create a new database with the name “shop”:

create database
Now, I created a new table called “products” with 4 fields:
create table

The fields will be “id” (AUTO_INCREMENT, INT, 3), “name” (VARCHAR, 20), “description” (VARCHAR, 80) and “price” (FLOAT):
create fields

In this table I have inserted 5 products with name, description and price:
database products

Step 2 – index.php

<html>
<head>
<title>Example AJAX with JSON, jQuery, PHP and MySQL</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="code.js"></script>
<style>
#html {
background-color: #f3e4cf;
}
.name_product {
border: 1px solid #000;
padding: 10px;
background-color: #d29c4e;
color: #fff;
cursor: pointer;
}
.data_product {
border: 1px solid #000;
padding: 10px;
background-color: #9a7a4d;
color: #fff;
}
</style>

</head>
<body>

<?php

$con = mysql_connect("localhost", "root", "root");

if (!$con) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db("shop", $con);

$result = mysql_query("SELECT id, name FROM `products`") or die("Error");

while ($products = mysql_fetch_assoc($result)) {
echo "<div id='" . $products[id] . "' class='name_product'>" . $products[name] . "</div>";
echo "<div id='data" . $products[id] . "' class='data_product'></div><br/>";
}
?>

</body>
</html>

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




 
Leave a Comment
Your comment: