Working with Ajax and JSON

Ajax means Asynchronous JavaScript and XML. its a very useful technique. normally ajax return output as xml format. xml is commonly used in web technology. but processing it and defining it some time difficult.But JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.let see how it work with a easy example.
let a html file called index.html it contain this

<html>
<head>
<title> ajax with php </title>
<script type=”text/JavaScript” src=”ajax.js”></script>
</head>
<body onload=’ajaxprocess()’>
Whats is your name:
<input type=”text” id=”name” />
<div id=”message” />
</body>
</html>

and ajax.js file process the Ajax request.
in here first need to create an request then process it

var xmlhttp= cr();

function cr()
{
var xmlhttp;
// for Microsoft ie 6+
if(window.ActiveXObject)
{
try
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}
catch(e)
{
xmlhttp=false;
}
}
// for mozilla or other browser
else
{
try{
xmlhttp=new XMLHttpRequest();
}
catch(e)
{
xmlhttp=false;
}
}

if(!xmlhttp)
alert("Error creating the file");
else
return xmlhttp;
}

after that we need to write the ajaxprocess() function

function ajaxprocess()
{
if(xmlhttp.readyState ==4 || xmlhttp.readyState ==0)
{
name=encodeURIComponent(document.getElementById("name").value);
// get data from name field
xmlhttp.open("GET","ajax.php?name=" + name, true);
// call the php function for processing data
xmlhttp.onreadystatechange = handle;
xmlhttp.send(null);
}
else
{
setTimeout('ajaxprocess()',1000);
}
}


Now we need return data from server add to the main page. return data
are xml format

function handle()
{
if(xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
response = xmlhttp.responseXML; // response from server
xmldomelement = response.documentElement;
// get the message
mess = xmldomelement.firstChild.data;
document.getElementById("message").innerHTML=''+mess+'';
setTimeout('ajaxprocess()',1000);
}
else
{
aleart("There is a problem accessing Server: "+xmlhttp.statusText);
}
}

}
now the ajax.php file looks like
<?php

header(‘Content-Type: text/xml’);

echo ‘<?xml version =”1.0″ encoding =”UTF-8″ standalone=”yes”?>’;

echo ‘<response>’;

$name = $_GET['name'];

$username = array(‘MAHFUZ’,'RANA’,'YOUSUF’,'MEHEDY’);

if(in_array(strtoupper($name),$username))

echo ‘Hello ‘.htmlentities($name).’!';

else if(trim($name) == ”)

echo ‘Enter a name ‘;

else

echo htmlentities($name).’, i donot know’;

echo’</response>’;

?>

thats the normal ajax with xml. but if we want to process this with json
we need some change.

function ajaxprocess()
{
if(xmlhttp.readyState ==4 || xmlhttp.readyState ==0)
{
name=encodeURIComponent(document.getElementById("name").value);
xmlhttp.open("GET","json.php?name=" + name, true);
xmlhttp.onreadystatechange = handle;
xmlhttp.send(null);
}
else
{
setTimeout('ajaxprocess()',1000);
}
}

function handle()
{
if(xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
card = eval("(" + xmlhttp.responseText + ")");
//eval function process the json data
mess= card.name;

document.getElementById("message").innerHTML = ''+mess+'';
setTimeout('ajaxprocess()',1000);
}
else
{
aleart("There is a problem accessing Server: "+xmlhttp.statusText);
}
}
}

and the json.php file is

<?php

header(‘Content-Type: text/JavaScript’);

// json code start with {

echo ‘{ “name” :’;

$name = $_GET['name'];

$username = array(‘MAHFUZ’,'RANA’,'YOUSUF’,'MEHEDY’);

if(in_array(strtoupper($name),$username))

echo ‘”Hello ‘.htmlentities($name).’!”‘;

else if(trim($name) == ”)

echo ‘”Enter a name “‘;

else

echo ‘”‘.htmlentities($name).’, i donot know”‘;

echo’ }’;

// and end with this  }

?>

if we want to json encode with php we can use this

<?php

header(‘Content-Type: text/JavaScript’);

$name = $_GET['name'];

$username = array(‘MAHFUZ’,'RANA’,'YOUSUF’,'MEHEDY’);

if(in_array(strtoupper($name),$username))

$m=’Hello’.htmlentities($name).’!';

else if(trim($name) == ”)

$m=’Enter a name ‘;

else

$m=htmlentities($name).’, i donot know’;

echo json_encode($m);

// json_encode() is a php function for json encoding json_decode() for decoding

?>

thats all now play with your code what you want. but now we do not need such line of code for processing the ajax .with JQuery we can do this with only two line of code

$.ajax() function.
that will be my next post.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.