Unit Iv

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

Advanced Java Script-JQuery/AJAX/JSON/Angular JS 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 −

 Browser-based presentation using HTML and Cascading Style Sheets (CSS).


 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
 JavaScript to make everything happen.

Advantages of jQuery Ajax:


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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

How AJAX Works

1. An event occurs in a web page (the page is loaded, a button is clicked)

2. An XMLHttpRequest object is created by JavaScript

3. The XMLHttpRequest object sends a request to a web server

4. The server processes the request

5. The server sends a response back to the web page

6. The response is read by JavaScript

7. Proper action (like page update) is performed by JavaScript

2. Explain the procedure for getting database data using jQuery-AJAX?

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 employee table and insert records.


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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

To Add, Edit And Delete Records It Takes Only Three Steps:-


1. Make a PHP file to display database records
2. Make a js file and define scripting
3. Make a PHP file for database operations

Step 1.Make a PHP file to display database records


We make a PHP file and save it with a name display_records.php
// Database Structure
CREATE TABLE `user_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

<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.

Step 2.Make a js file and define scripting


We make a js file and save it with a name modify_records.js
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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 delete_row() function we again get the row id and send it to our


modify_records.php page for deletion.

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.

Step 3.Make a PHP file for database operations


We make a PHP file and save it with a name modify_records.php
<?php
$host="localhost";
$username="root";
$password="";
$databasename="sample";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
if(isset($_POST['edit_row']))
{
$row=$_POST['row_id'];
$name=$_POST['name_val'];
$age=$_POST['age_val'];
mysql_query("update user_detail set name='$name',age='$age' where id='$row'");
echo "success";
exit();
}
if(isset($_POST['delete_row']))
{
$row_no=$_POST['row_id'];
mysql_query("delete from user_detail where id='$row_no'");
echo "success";
exit();
}
if(isset($_POST['insert_row']))
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

{
$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.

4. How to develop Grid using jQuery-AJAX?

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:

The procedure for inserting grid:


Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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;

CREATE TABLE product


(
product_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL DEFAULT '',
price DECIMAL(10,2) NOT NULL DEFAULT '0.00',
on_promotion TINYINT NOT NULL DEFAULT '0',
PRIMARY KEY (product_id)
);

INSERT INTO product(name, price, on_promotion)


VALUES('Santa Costume', 14.99, 0);

2. Verify that your table has been correctly created.


3. Create a folder named grid in your ajax folder.
4. Copy the scripts folder from the code download to your grid folder.
5. Create a file named config.php in your grid folder with the following contents:
<?php
// defines database connection data
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'ajax');
?>
6. Create a file named error_handler.php in your grid folder and type the
following code in it:
<?php
// set the user error handler method to be error_handler
set_error_handler('error_handler', E_ALL);
// error handler function
function error_handler($errNo, $errStr, $errFile, $errLine)
{
// clear any output that has already been generated
ob_clean();
// output the error message
$error_message = 'ERRNO: ' . $errNo . chr(10) .
'TEXT: ' . $errStr . chr(10) .
'LOCATION: ' . $errFile .
', line ' . $errLine;
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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');

// the default action is 'load'


$action = 'load';
if(isset($_GET['action']))
$action = $_GET['action'];

// load the grid


if($action == 'load')
{
// get the requested page
$page = $_POST['page'];
// get how many rows we want to have into the grid
$limit = $_POST['rows'];
// get index row - i.e. user click to sort
$sidx = $_POST['sidx'];
// get the direction
$sord = $_POST['sord'];

$grid = new Grid($page, $limit, $sidx, $sord);


$response->page = $page;
$response->total = $grid->getTotalPages();
$response->records = $grid->getTotalItemsCount();
$currentPageItems = $grid->getCurrentPageItems();
for($i=0;$i<count($currentPageItems);$i++) {
$response->rows[$i]['id'] =
$currentPageItems[$i]['product_id'];
$response->rows[$i]['cell']=array(
$currentPageItems[$i]['product_id'],
$currentPageItems[$i]['name'],
$currentPageItems[$i]['price'],
$currentPageItems[$i]['on_promotion']
);
}
echo json_encode($response);
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

// save the grid data


elseif ($action == 'save')
{
$product_id = $_POST['id'];
$name = $_POST['name'];
$price = $_POST['price'];
$on_promotion = ($_POST['on_promotion'] =='Yes') ? 1 : 0;
$grid = new Grid();
echo $grid->updateItem
($product_id, $on_promotion, $price, $name);
}
?>
8. Create a file named grid.class.php and type the following code in it:
<?php
// load configuration file
require_once('config.php');
// start session
session_start();

// includes functionality to manipulate the products list


class Grid
{
// grid pages count
private $mTotalPages;
// grid items count
private $mTotalItemsCount;
private $mItemsPerPage;
private $mCurrentPage;

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;
}

// read a page of products and save it to $this->grid


public function getCurrentPageItems()
{
// create the SQL query that returns a page of products
$queryString = 'SELECT * FROM product';
$queryString .= ' ORDER BY ' .
$this->mMysqli->real_escape_string($this->mSortColumn) .
' ' . $this->mMysqli->real_escape_string(
$this->mSortDirection);
// do not put $limit*($page - 1)
$start = $this->mItemsPerPage * $this->mCurrentPage –
$this->mItemsPerPage;
if ($start<0) $start = 0;
$queryString .= ' LIMIT ' . $start . ',' . $this-
>mItemsPerPage;

// execute the query


if ($result = $this->mMysqli->query($queryString))
{
for($i = 0; $items[$i] = $result->fetch_assoc(); $i++) ;

// Delete last empty item


array_pop($items);

// close the results stream and return the results


$result->close();
return $items;
}
}
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

public function getTotalPages()


{
return $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;

// execute the SQL command


$this->mMysqli->query($queryString);
return $this->mMysqli->affected_rows;
}

// returns the total number of records for the grid


private function countAllItems()
{
// the query that returns the record count
$count_query = 'SELECT COUNT(*) FROM product';
// execute the query and fetch the result
if ($result = $this->mMysqli->query($count_query))
{
// retrieve the first returned row
$row = $result->fetch_row();
// close the database handle
$result->close();
return $row[0];
}
return 0;
}

public function getTotalItemsCount()


{
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

return $this->mTotalItemsCount;
}

// end class Grid


}
?>

Finally, create index.html with the following code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>jqGrid Demo</title>
<link rel="stylesheet" type="text/css"
href="scripts/themes/green/grid.css"
title="coffee"
media="screen" />
<link rel="stylesheet" type="text/css"
media="screen"
href="themes/jqModal.css" />
<script src="scripts/jquery-1.3.2.js"
type="text/javascript"></script>
<script src="scripts/jquery.jqGrid.js"
type="text/javascript"></script>
<script src="scripts/js/jqModal.js"
type="text/javascript"></script>
<script src="scripts/js/jqDnR.js"
type="text/javascript"></script>
</head>
<body>
<h2>My Grid Data</h2>
<table id="list" class="scroll"
cellpadding="0"
cellspacing="0">
</table>
<div id="pager" class="scroll"
style="text-align:center;">
</div>
<script type="text/javascript">
var lastSelectedId;
$('#list').jqGrid({
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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

9. Load http://localhost/ajax/grid, and check that your grid works as presented


in Figure.

5. What is JSON? Write the syntax for JSON?


JSON stands for JavaScript Object Notation. JSON objects are used for transferring
data between server and client, XML serves the same purpose. However JSON
objects have several advantages over XML. JSON is an open standard for exchanging
data on the web. It supports data structures like object and array. So it is easy to write
and read data from JSON.
Features of JSON:
o JSON is an open standard data-interchange format.
o JSON is lightweight and self describing.
o JSON is originated from JavaScript.
o JSON is easy to read and write.
o JSON is language independent.
o JSON supports data structures such as array and objects.
o Text based, human readable data exchange format
Why use JSON?
Standard Structure: As we have seen so far that JSON objects are having a standard
structure that makes developers job easy to read and write code, because they know
what to expect from JSON.
Light weight: When working with AJAX, it is important to load the data quickly and
asynchronously without requesting the page re-load. Since JSON is light weighted, it
becomes easier to get and load the requested data quickly.
Scalable: JSON is language independent, which means it can work well with most of
the modern programming language. Let’s say if we need to change the server side
language, in that case it would be easier for us to go ahead with that change as JSON
structure is same for all the languages.

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";

Delete Object Properties


Use the delete keyword to delete properties from a JSON object:
Example
delete myObj.cars.car2;

Reading JSON objects using jQuery:


JSON.parse()
A common use of JSON is to exchange data to/from a web server.When receiving
data from a web server, the data is always a string.Parse the data with JSON.parse(),
and the data becomes a JavaScript object.
Example - Parsing JSON
Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
Make sure the text is written in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
JSON From the Server
You can request JSON from the server by using an AJAX request
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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();

7. Write about JSON arrays?


Arrays in JSON are almost the same as arrays in JavaScript.In JSON, array values
must be of type string, number, object, array, boolean or null.In JavaScript, array
values can be all of the above, plus any other valid JavaScript expression, including
functions, dates, and undefined.
[ "Ford", "BMW", "Fiat" ]
Arrays in JSON Objects
Arrays can be values of an object property:
Example
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
Accessing Array Values
You access the array values by using the index number:
Example
x = myObj.cars[0];
Looping Through an Array
You can access array values by using a for-in loop:
Example
for (i in myObj.cars) {
    x += myObj.cars[i];
}
or you can use a for loop:
Example
for (i = 0; i < myObj.cars.length; i++) {
    x += myObj.cars[i];
}
Nested Arrays in JSON Objects
Advanced Java Script-JQuery/AJAX/JSON/Angular JS UNIT IV

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];

You might also like