Unit Iv
Unit Iv
Unit Iv
UNIT-IV
AJAX
1. What is AJAX? What is the need of AJAX in real web sites?
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for
creating better, faster, and more interactive web applications with the help of XML,
HTML, CSS, and Java Script.
Ajax uses XHTML for content, CSS for presentation, along with Document Object
Model and JavaScript for dynamic content display.
Conventional web applications transmit information to and from the sever using
synchronous requests. It means you fill out a form, hit submit, and get directed to a
new page with new information from the server.
With AJAX, when you hit submit, JavaScript will make a request to the server,
interpret the results, and update the current screen. In the purest sense, the user
would never know that anything was even transmitted to the server.
XML is commonly used as the format for receiving server data, although any
format, including plain text, can be used.
AJAX is a web browser technology independent of web server software.
A user can continue to use the application while the client program requests
information from the server in the background.
Intuitive and natural user interaction. Clicking is not required, mouse movement is
a sufficient event trigger.
Data-driven as opposed to page-driven.
Rich Internet Application Technology
AJAX is the most viable Rich Internet Application (RIA) technology so far. It is
getting tremendous industry momentum and several tool kit and frameworks are
emerging. But at the same time, AJAX has browser incompatibility and it is
supported by JavaScript, which is hard to maintain and debug.
AJAX is Based on Open Standards
AJAX is based on the following open standards −
1. Cross-browser support
2. Simple methods to use
3. Ability to send GET and POST requests
4. Ability to Load JSON, XML, HTML or Scripts
In this article, you will see how to fetch data from a mysql database using JQuery
AJAX and php. JQuery AJAX allows us to update a page’s content without reloading
the page.
1. Create Table
create table employee(id int(10) not null primary key auto_increment, firstname
varchar(20), lastname varchar(20));
insert into employee(firstname,lastname) values('Puneet','Aggarwal');
insert into employee(firstname,lastname) values('Sahil','Garg');
2. Create PHP
Now create a php file that connects to database and encode the result in JSON format.
Following is employee.php file
<?php
//connect to the mysql
$db = @mysql_connect('localhost', 'username', 'password') or die("Could not connect
database");
@mysql_select_db('databasename', $db) or die("Could not select database");
//database query
$sql = @mysql_query("select firstname,lastname from employee");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
//echo result as json
echo json_encode($rows);
?>
3. Create Script
Now create a script file that calls employee.php using jquery ajax and then parse the
response from employee.php
Following is ajax.js file
$(document).ready(function() {
$("#ajaxButton").click(function() {
$.ajax({
type: "Post",
url: "employee.php",
success: function(data) {
var obj = $.parseJSON(data);
var result = "<ul>"
$.each(obj, function() {
result = result + "<li>First Name : " + this['firstname'] + " , Last
Name : " + this['lastname'] + "</li>";
});
result = result + "</ul>"
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
$("#result").html(result);
}
});
});
});
4. Create Front End
Now create a html file that displays the results parsed in ajax.js
Following is index.html file
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.6.2.js"></script>
<script language="javascript" type="text/javascript" src="ajax.js"></script>
</head>
<body>
<input type="button" value="Click Here" id="ajaxButton"/>
<div id="result"></div>
</body>
</html>
Following screen will be displayed when you click the button as shown in Figure 1.1
3. Explain the procedure for inserting, updating and deleting database data
using jQuery-AJAX?
In this example we will discuss how to add, edit and delete records using jQuery,
Ajax, PHP and MySQL. In this way you can do any modification in MySQL database
dynamically means without refreshing your page. In this you can insert new rows in
database, edit existing row and update the row in database and delete any row in
database. You may also like delete multiple records from MySQL using PHP.
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="modify_records.js"></script>
</head>
<body>
<div id="wrapper">
<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$select =mysql_query("SELECT * FROM user_detail");
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
?>
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<?php
while ($row=mysql_fetch_array($select))
{
?>
<tr id="row<?php echo $row['id'];?>">
<td id="name_val<?php echo $row['id'];?>"><?php echo $row['name'];?></td>
<td id="age_val<?php echo $row['id'];?>"><?php echo $row['age'];?></td>
<td>
<input type='button' class="edit_button" id="edit_button<?php echo $row['id'];?>"
value="edit" onclick="edit_row('<?php echo $row['id'];?>');">
<input type='button' class="save_button" id="save_button<?php echo $row['id'];?>"
value="save" onclick="save_row('<?php echo $row['id'];?>');">
<input type='button' class="delete_button" id="delete_button<?php echo
$row['id'];?>" value="delete" onclick="delete_row('<?php echo $row['id'];?>');">
</td>
</tr>
<?php
}
?>
<tr id="new_row">
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_age"></td>
<td><input type="button" value="Insert Row" onclick="insert_row();"></td>
</tr>
</table>
</div>
</body>
</html>
In this step we create a database table 'user_detail' and insert some rows and then
display the records to edit, delete and create a new row having textbox and buttons to
insert new records in database.We insert modify_records.js file which we were going
to create in next step.You may also like add, edit and delete rows from table
dynamically using JavaScript.
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text'
id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text'
id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_text"+id).value;
var age=document.getElementById("age_text"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td
id='name_val"+id+"'>"+name+"</td><td
id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button'
id='edit_button"+id+"' value='edit' onclick='edit_row("+id+");'/><input type='button'
class='save_button' id='save_button"+id+"' value='save'
onclick='save_row("+id+");'/><input type='button' class='delete_button'
id='delete_button"+id+"' value='delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
In this step we create four funtions to edit, save, delete and insert records.In
edit_row() function we get row id and get the name and age text and then insert the
textbox with age and name value in both the columns to edit the text and then display
the save button to save the records.
In save_row() function we get the row id and then with the help of row id get the
name and age value then send the values to modify_records.php page to update the
record and if the record updated successfully we display the edited record in there
respective row.
In insert_row() function we get the value of new_name and new_age from the textbox
we made to insert new rows and send the data to modify_records.php page to insert
new record in database and if record inserted successfully we display the new record
in our table.
{
$name=$_POST['name_val'];
$age=$_POST['age_val'];
mysql_query("insert into user_detail values('','$name','$age')");
echo mysql_insert_id();
exit();
}
?>
In this step we create three isset() conditions to edit, delete and insert records in
database.In first isset() condition we get all the three value and update the row having
that particular row id and display 'success'.In second isset() condition we get the row
id and delete the row having that id.In third isset() condition we get the name and age
value and then insert in our database and then display the inserted id to create a new
table row in our table in display_records.php page.Always validate data before and
after submitting the form to prevent sql injections.
One of the most common ways to render data is in the form of a data grid. Grids are
used for a wide range of tasks from displaying address books to controlling
inventories and logistics management. Because centralizing data in repositories has
multiple advantages for organizations, it wasn't long before a large number of
applications were being built to manage data through the Internet and intranet
applications by using data grids.
Our finished grid will look like this:
1. Before we do anything, we'll need some data to work with. Create your products
table executing the following SQL code in phpMyAdmin. (For briefness, we
included here only a few of the product entries that you can find in the
downloadable version.)
USE ajax;
echo $error_message;
// prevent processing any more PHP scripts
exit;
}
?>
7. Create a file named grid.php and type the following code in it:
<?php
// load error handling script and the Grid class
require_once('error_handler.php');
require_once('grid.class.php');
private $mSortColumn;
private $mSortDirection;
// database handler
private $mMysqli;
// class constructor
function __construct($currentPage=1, $itemsPerPage=5,
$sortColumn='product_id', $sortDirection='asc')
{
// create the MySQL connection
$this->mMysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD,
DB_DATABASE);
$this->mCurrentPage = $currentPage;
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
$this->mItemsPerPage = $itemsPerPage;
$this->mSortColumn = $sortColumn;
$this->mSortDirection = $sortDirection;
// call countAllRecords to get the number of grid records
$this->mTotalItemsCount = $this->countAllItems();
if($this->mTotalItemsCount >0)
$this->mTotalPages =
ceil($this->mTotalItemsCount/$this->mItemsPerPage);
else
$this->mTotalPages=0;
if($this->mCurrentPage > $this->mTotalPages)
$this->mCurrentPage = $this->mTotalPages;
}
// update a product
public function updateItem($id, $on_promotion, $price, $name)
{
// escape input data for safely using it in SQL statements
$id = $this->mMysqli->real_escape_string($id);
$on_promotion = $this->mMysqli-
>real_escape_string($on_promotion);
$price = $this->mMysqli->real_escape_string($price);
$name = $this->mMysqli->real_escape_string($name);
// build the SQL query that updates a product record
$queryString = 'UPDATE product SET name="' . $name . '", ' .
'price=' . $price . ',' .
'on_promotion=' . $on_promotion .
' WHERE product_id=' . $id;
return $this->mTotalItemsCount;
}
url:'grid.php',
datatype: 'json',
mtype: 'POST',
colNames:['ID','Name', 'Price', 'Promotion'],
colModel:[
{name:'product_id',index:'product_id',
width:55,editable:false},
{name:'name',index:'name', width:100,editable:true,
edittype:'text',editoptions:{size:30,maxlength:50}},
{name:'price',index:'price', width:80,
align:'right',formatter:'currency', editable:true},
{name:'on_promotion',index:'on_promotion', width:80,
formatter:'checkbox',editable:true,
edittype:'checkbox'}
],
rowNum:10,
rowList:[5,10,20,30],
imgpath: 'scripts/themes/green/images',
pager: $('#pager'),
sortname: 'product_id',
viewrecords: true,
sortorder: "desc",
caption:"JSON Example",
width:600,
height:250,
onSelectRow: function(id){
if(id && id!==lastSelectedId){
$('#list').restoreRow(lastSelectedId);
$('#list').editRow(id,true,null,onSaveSuccess);
lastSelectedId=id;
}
},
editurl:'grid.php?action=save'
});
function onSaveSuccess(xhr)
{
response = xhr.responseText;
if(response == 1)
return true;
return false;
}
</script>
</body>
</html>
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
JSON Syntax
JSON defines only two data structures: objects and arrays. An object is a set of name-
value pairs, and an array is a list of values. JSON defines seven value types: string,
number, object, array, true, false, and null.
The following example shows JSON data for a sample object that contains name-
value pairs. The value for the name "phoneNumbers" is an array whose elements are
two objects.
{
"firstName": "Duke",
"lastName": "Java",
"age": 18,
"streetAddress": "100 Internet Dr",
"city": "JavaTown",
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
"state": "JA",
"postalCode": "12345",
"phoneNumbers": [
{ "Mobile": "111-111-1111" },
{ "Home": "222-222-2222" }
]
}
JSON has the following syntax.
Objects are enclosed in braces ({}), their name-value pairs are separated by a
comma (,), and the name and value in a pair are separated by a colon (:). Names
in an object are strings, whereas values may be of any of the seven value types,
including another object or an array.
Arrays are enclosed in brackets ([]), and their values are separated by a comma
(,). Each value in an array may be of a different type, including another array or
an object.
When objects and arrays contain other objects or arrays, the data has a tree-like
structure.
6. Write about JSON objects?
Values in JSON can be objects. JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type (string, number,
object, array, boolean or null).
Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
{ "name":"John", "age":30, "car":null }
Accessing Object Values
You can access the object values by using dot (.) notation:
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
You can also access the object values by using bracket ([]) notation:
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
Looping an Object
You can loop through object properties by using the for-in loop:
Example
myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV
document.getElementById("demo").innerHTML += x;
}
Nested (complex) JSON Objects
Values in a JSON object can be another JSON object.
Example
myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
Modify Values
You can use the dot notation to modify any value in a JSON object:
Example
myObj.cars.car2 = "Mercedes";
As long as the response from the server is written in JSON format, you can parse the
string into a JavaScript object.
Example
Use the XMLHttpRequest to get data from the server:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
Values in an array can also be another array, or even another JSON object:
Example
myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
for (i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
Modify Array Values
Use the index number to modify an array:
Example
myObj.cars[1] = "Mercedes";
Delete Array Items
Use the delete keyword to delete items from an array:
Example
delete myObj.cars[1];