Notes Javascript - AJAX, JSON & XML Samples
AJAX, JSON & XML Samples
This is a code-only page.
HTML
GET sends data via the querystring. In this example it just sends a single integer.
<a href="javascript:standardAjaxGet1(10)" class="btn btn-bs-primary">Standard AJAX - GET</a><br/>
Javascript
/* THE FOLLOWING FUNCTION USES STANDARD JAVASCRIPT TO MAKE AN AJAX GET CALL. */ function standardAjaxGet1(ItemNum) { // Create an XML HTTP Object if (window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest();}// For IE7+, All else {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} // For IE6-5 xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtOutput").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","AjaxResponse1.php?ItemNum=" + ItemNum,true); xmlhttp.send(); } /* THIS FUNCTION TAKES THE RESPONSE TEXT PARAMETER respText AND DISPLAYS IT IN THE DIV WITH ID = results1 */ function ProcessResponse1(respText) { var divResult = document.getElementById("results1"); divResult.innerHTML = respText; }
AjaxResponse1.php
The PHP server side file gets the single integer sent and wraps it in some simple HTML and returns it to the client-side calling function.
<?php // SIMPLE AJAX RESPONSE SCRIPT - GET // GET QUERY STRING $ItemNum=$_GET['ItemNum']; $StrHtm=""; $StrHtm = "<br/>Output From AjaxResponse1.php AJAX Get Call. ItemNum: ". $ItemNum ."<br/>"; echo $StrHtm; ?>
Standard AJAX - GET
Response
Post can send data as delimited string or as JSON. In this example, the code uses a delimited string built from hidden field values.
HTML
<input type="hidden" id="hidVal1_1" value="12"/> <input type="hidden" id="hidVal1_2" value="Some Text"/> <input type="hidden" id="hidVal1_3" value="33.43"/> <a href="javascript:standardAjaxPost1()" class="btn btn-bs-primary">Standard AJAX - POST</a><br/>
Javascript
function standardAjaxPost1() { // PACKAGE THE SENDING DATA var hidVal1=document.getElementById("hidVal1_1"); var hidVal2=document.getElementById("hidVal1_2"); var hidVal3=document.getElementById("hidVal1_3"); var data=""; data += "hidVal1=" + hidVal1.value; data += "&hidVal2=" + hidVal2.value; data += "&hidVal3=" + hidVal3.value; // CREATE AN XML HTTP OBJECT if (window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest();} // FOR IE7+, ALL else {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} // FOR IE6-5 xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { ProcessResponse3(xmlhttp.responseText); } } xmlhttp.open("POST","AjaxResponse2.php",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send(data); } function ProcessResponse3(respText) { var divResult = document.getElementById("results2"); divResult.innerHTML = respText; }
Server Side PHP
<?php // AJAX RESPONSE SCRIPT AjaxResponse2.php // GET POST VALUES $hidVal1 = $_POST['hidVal1']; $hidVal2 = $_POST['hidVal2']; $hidVal3 = $_POST['hidVal3']; $StrHtm = ""; $StrHtm = "<br/>Output From AJAX Post Call.<br/>hidVal1: ". $hidVal1 ."<br/>hidVal2: ". $hidVal2 ."<br/>hidVal3: ". $hidVal3 ."<br/>"; echo $StrHtm; ?>
Standard AJAX - POST
Response
HTML
This example uses a form with the id of form2. The form fields are the hidden items hidVal2_1, hidVal2_2, and hidVal2_3; and the text form fields txtName and txtOccupation.
<form id="form2"> <input type="hidden" id="hidVal2_1" value="12"/> <input type="hidden" id="hidVal2_2" value="Some Text"/> <input type="hidden" id="hidVal2_3" value="33.43"/> <table> <tbody> <tr> <th>Name</th><td><input id="txtName" type="text" value="Dirk" /></td> </tr> <tr> <th>Occupation</th><td><input id="txtOccupation" type="text" value="Software Developer" /></td> </tr> </tbody> </table> </form> <a href="javascript:standardAjaxPost2()" class="btn btn-bs-primary">Standard AJAX - JSON</a>
Javascript
The javascript function first gets reference to all of the form fields, then a JSON object is created called data.
The JSON object is loaded with values from the referenced form fields.
The JSON object is then stringified and stored in the variable json_str.
An XML HTTP Object is created.
It's Request Header is set to the content type of application/json.
JSON Response Processing
The response from the PHP file is JSON, but it must be parsed by javascript using JSON.parse() before it can be used.
function standardAjaxPost2() { // PACKAGE THE SENDING DATA var hidVal1=document.getElementById("hidVal2_1"); var hidVal2=document.getElementById("hidVal2_2"); var hidVal3=document.getElementById("hidVal2_3"); var txtName=document.getElementById("txtName"); var txtOccupation=document.getElementById("txtOccupation"); var data = {}; data.hidVal1 = hidVal1.value; data.hidVal2 = hidVal2.value; data.hidVal3 = hidVal3.value; data.name = txtName.value; data.occupation = txtOccupation.value; var json_str = JSON.stringify(data); // Create an XML HTTP Object if (window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest();}// For IE7+, All else {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} // For IE6-5 xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { ProcessResponse3(xmlhttp.responseText); } } xmlhttp.open("POST","AjaxResponse3.php",true); xmlhttp.setRequestHeader("Content-Type","application/json;charset=UTF-8"); xmlhttp.send(json_str); } function ProcessResponse3(respText) { var divResult = document.getElementById("results3"); var rtObj = JSON.parse(respText); var resp_str = ""; resp_str = "hidVal1: "+ rtObj.hidVal1 +"<br/>" resp_str += "hidVal2: "+ rtObj.hidVal2 +"<br/>" resp_str += "hidVal3: "+ rtObj.hidVal3 +"<br/>" resp_str += "Name: "+ rtObj.name +"<br/>" resp_str += "Occupation: "+ rtObj.occupation +"<br/>" resp_str += "authorFirst: "+ rtObj.authorFirst +"<br/>" resp_str += "authorLast: "+ rtObj.authorLast +"<br/>" divResult.innerHTML = resp_str; }
Server Side PHP
Retrieving the JSON sent cannot be done with $_POST[].
It must be obtained by using php://input as the parameter to the PHP file_get_contents() function.
php://input is a read-only stream that allows you to read raw data from the request body.
php://input is not available with enctype="multipart/form-data".
Once the raw data is retrieved it must be decoded using the PHP function json_decode before it can be used.
<?php $json = file_get_contents('php://input'); $data = json_decode($json); $hidVal1=$data->hidVal1; $hidVal2=$data->hidVal2; $hidVal3=$data->hidVal3; $name=$data->name; $occupation=$data->occupation; $output = array('authorFirst' => 'Dirk', 'authorLast' => 'Harriman', 'hidVal1' => $hidVal1, 'hidVal2' => $hidVal2, 'hidVal3' => $hidVal3, 'name' => $name, 'occupation' => $occupation); header('Content-Type:application/json'); echo json_encode($output, JSON_FORCE_OBJECT); ?>
Standard AJAX - JSONResponse
This example uses the FormData object.
This works similar to the jQuery serialize function.
I could not get this to work without removing the Content-Type.
HTML
<form id="form3" name="form3"> <input type="hidden" name="hidVal3_1" id="hidVal3_1" value="13"/> <input type="hidden" name="hidVal3_2" id="hidVal3_2" value="Some Other Text"/> <input type="hidden" name="hidVal3_3" id="hidVal3_3" value="99.99"/> <table> <tbody> <tr> <th>Name</th> <td> <input name="txtName3" id="txtName3" type="text" value="Dirk" /> </td> </tr> <tr> <th>Occupation</th> <td> <input name="txtOccupation3" id="txtOccupation3" type="text" value="Software Developer" /> </td> </tr> </tbody> </table> </form> <a href="javascript:standardAjaxPost3()" class="btn btn-bs-primary">Standard AJAX - FormData</a>
Javascript
function standardAjaxPost3() { // PACKAGE THE SENDING DATA var form3 = document.forms.form3; var formData = new FormData(form3); // ADD A COUPLE OF FIELDS TO THE FORM DATA formData.append("userName", "Drogo"); formData.append("accountNum", 123456); // CREATE AN XML HTTP OBJECT if (window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest();}// For IE7+, ALL else {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} // For IE6-5 xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { ProcessResponse4(xmlhttp.responseText); } } xmlhttp.open("POST","AjaxResponse4.php"); xmlhttp.send(formData); } function ProcessResponse4(respText) { var divResult = document.getElementById("results4"); divResult.innerHTML = respText; }
Server Side - PHP
<?php // GET POST VALUES $hidVal1 = $_POST['hidVal3_1']; $hidVal2 = $_POST['hidVal3_2']; $hidVal3 = $_POST['hidVal3_3']; $name = $_POST['txtName3']; $occupation = $_POST['txtOccupation3']; $userName = $_POST['userName']; $accountNum = $_POST['accountNum']; $strHtm = "<br/>Output From AJAX Post Call.<br/>"; $strHtm .= "hidVal1: ". $hidVal1 ."<br/>"; $strHtm .= "hidVal2: ". $hidVal2 ."<br/>"; $strHtm .= "hidVal3: ". $hidVal3 ."<br/>"; $strHtm .= "Name: ". $name ."<br/>"; $strHtm .= "Occupation: ". $occupation ."<br/>"; $strHtm .= "userName: ". $userName ."<br/>"; $strHtm .= "accountNum: ". $accountNum ."<br/>"; echo $strHtm; ?>
Standard AJAX - FormDataResponse
By default, jQuery Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
HTML
<a href="javascript:jQueryAjaxGet1(21)" class="btn btn-bs-primary">jQuery AJAX - GET</a><br/>
jQuery
/* THIS FUNCTION MAKES A jQuery AJAX CALL */ function jQueryAjaxGet1(ItemNum) { $.ajax({ method: "GET", url: "AjaxResponse1.php?ItemNum=" + ItemNum, }) .done(function(msg){ ProcessResponse2(msg); }) } /* THIS FUNCTION TAKES THE RESPONSE TEXT PARAMETER respText AND DISPLAYS IT IN THE DIV WITH ID = results7 */ function ProcessResponse2(respText) { var divResult = document.getElementById("results7"); divResult.innerHTML = respText; }
AjaxResponse1.php
<?php // SIMPLE AJAX RESPONSE SCRIPT - GET // GET QUERY STRING $ItemNum=$_GET['ItemNum']; $StrHtm=""; $StrHtm = "<br/>Output From AjaxResponse1.php AJAX Get Call. ItemNum: ". $ItemNum ."<br/>"; echo $StrHtm; ?>
jQuery AJAX - GET
Response
HTML
<form id="formJQ1"> <input type="hidden" id="hidValJQ1_1" value="122"/> <input type="hidden" id="hidValJQ1_2" value="This is jQuery Text"/> <input type="hidden" id="hidValJQ1_3" value="148.43"/> <table> <tbody> <tr> <th>Name</th><td><input id="txtNameJQ1" type="text" value="Jack" /></td> </tr> <tr> <th>Occupation</th><td><input id="txtJobJQ1" type="text" value="Software Developer" /></td> </tr> </tbody> </table> </form> <a href="javascript:jQueryAjaxPost1()" class="btn btn-bs-primary">jQuery AJAX - POST (Delimited String)</a><br/> <br/> <h3>Response</h3> <div class="response" id="results8"></div>
jQuery
function jQueryAjaxPost1() { // PACKAGE THE SENDING DATA var hidVal1 = document.getElementById("hidValJQ1_1"); var hidVal2 = document.getElementById("hidValJQ1_2"); var hidVal3 = document.getElementById("hidValJQ1_3"); var txtName = document.getElementById("txtNameJQ1"); var txtJob = document.getElementById("txtJobJQ1"); var data_str = ""; data_str += "hidVal1=" + hidVal1.value; data_str += "&hidVal2=" + hidVal2.value; data_str += "&hidVal3=" + hidVal3.value; data_str += "&txtName=" + txtName.value; data_str += "&txtJob=" + txtJob.value; $.ajax({ method: "POST", url: "AjaxResponse7.php", data: data_str }) .done(function(msg){ ProcessResponse8(msg); }) } function ProcessResponse8(respText) { var divResult = document.getElementById("results8"); divResult.innerHTML = respText; }
Server Side PHP
<?php // AJAX RESPONSE SCRIPT AjxPost1.php FOR Dev003.php if ($_SERVER["REQUEST_METHOD"] == "POST") { // GET POST VALUES $hidVal1 =$_POST['hidVal1']; $hidVal2 =$_POST['hidVal2']; $hidVal3 =$_POST['hidVal3']; $name =$_POST['txtName']; $job =$_POST['txtJob']; $StrHtm=""; $StrHtm = "<br/>Output From AJAX Post Call.<br/>"; $StrHtm .= "Name: ". $name ."<br/>"; $StrHtm .= "Job: ". $job ."<br/>"; $StrHtm .= "hidVal1: ". $hidVal1 ."<br/>"; $StrHtm .= "hidVal2: ". $hidVal2 ."<br/>"; $StrHtm .= "hidVal3: ". $hidVal3 ."<br/>"; echo $StrHtm; } else { echo "Method Not Post"; } ?>
jQuery AJAX - POST (Delimited String)Response
In this example the data is stored in a JSON object.
HTML
<form id="formJQ2"> <input type="hidden" id="hidValJQ2_1" value="122"/> <input type="hidden" id="hidValJQ2_2" value="This is jQuery Text"/> <input type="hidden" id="hidValJQ2_3" value="148.43"/> <table> <tbody> <tr> <th>Name</th><td><input id="txtNameJQ2" type="text" value="Jack" /></td> </tr> <tr> <th>Occupation</th><td><input id="txtJobJQ2" type="text" value="Software Developer" /></td> </tr> </tbody> </table> </form> <a href="javascript:jQueryAjaxPost2()" class="btn btn-bs-primary">jQuery AJAX - POST (JSON)</a> <h3>Response</h3> <div class="response" id="results9"></div>
jQuery
function jQueryAjaxPost2(){ // PACKAGE THE SENDING DATA var hidVal1 = document.getElementById("hidValJQ2_1"); var hidVal2 = document.getElementById("hidValJQ2_2"); var hidVal3 = document.getElementById("hidValJQ2_3"); var txtName = document.getElementById("txtNameJQ2"); var txtJob = document.getElementById("txtJobJQ2"); var data = {}; data.hidVal1 = hidVal1.value; data.hidVal2 = hidVal2.value; data.hidVal3 = hidVal3.value; data.name = txtName.value; data.job = txtJob.value; var json_str = JSON.stringify(data); $.ajax({ method: "POST", url: "AjaxResponse9.php", data: json_str, dataType: "json" }) .done(function(msg){ ProcessResponse9(msg); }) } function ProcessResponse9(respText) { var divResult = document.getElementById("results9"); var resp_str = ""; resp_str = "hidVal1: "+ respText.hidVal1 +"<br/>" resp_str += "hidVal2: "+ respText.hidVal2 +"<br/>" resp_str += "hidVal3: "+ respText.hidVal3 +"<br/>" resp_str += "Name: "+ respText.name +"<br/>" resp_str += "Occupation: "+ respText.job +"<br/>" resp_str += "authorFirst: "+ respText.authorFirst +"<br/>" resp_str += "authorLast: "+ respText.authorLast +"<br/>" divResult.innerHTML = resp_str; }
Server Side PHP
<?php // AJAX POSTED JSON DATA //json_decode $json = file_get_contents('php://input'); $data = json_decode($json); $hidVal1 = $data->hidVal1; $hidVal2 = $data->hidVal2; $hidVal3 = $data->hidVal3; $name = $data->name; $job = $data->job; $output = array('authorFirst' => 'Dirk', 'authorLast' => 'Harriman', 'hidVal1' => $hidVal1, 'hidVal2' => $hidVal2, 'hidVal3' => $hidVal3, 'name' => $name, 'job' => $job); header('Content-Type:application/json'); echo json_encode($output, JSON_FORCE_OBJECT); ?>
jQuery AJAX - POST (JSON)Response
Important Note: FormData uses the name field as opposed to the id field. Failure to include the name field will result in an error on the PHP side.
HTML
<form id="formJQ3"> <input type="hidden" name="hidValJQ3_1" id="hidValJQ3_1" value="122"/> <input type="hidden" name="hidValJQ3_2" id="hidValJQ3_2" value="This is jQuery Text"/> <input type="hidden" name="hidValJQ3_3" id="hidValJQ3_3" value="148.43"/> <table> <tbody> <tr> <th>Name</th><td><input name="txtNameJQ3" id="txtNameJQ3" type="text" value="John" /></td> </tr> <tr> <th>Occupation</th><td><input name="txtJobJQ3" id="txtJobJQ3" type="text" value="Software Developer" /></td> </tr> </tbody> </table> </form> <a href="javascript:jQueryAjaxPost3()" class="btn btn-bs-primary">jQuery AJAX - POST (FormData)</a> <h3>Response</h3> <div class="response" id="results10"></div>
jQuery
function jQueryAjaxPost3() { // PACKAGE THE SENDING DATA var form3 = document.forms.formJQ3; var formData = new FormData(form3); formData.append("userName", "Drogo"); formData.append("accountNum", 123456); $.ajax({ method: "POST", url: "AjaxResponse10.php", data: formData, processData: false, contentType: false, }) .done(function(msg){ ProcessResponse10(msg); }) } function ProcessResponse10(respText) { var divResult = document.getElementById("results10"); divResult.innerHTML = respText; }
Server Side PHP
<?php // GET POST VALUES $hidVal1 = $_POST['hidValJQ3_1']; $hidVal2 = $_POST['hidValJQ3_2']; $hidVal3 = $_POST['hidValJQ3_3']; $name = $_POST['txtNameJQ3']; $occupation = $_POST['txtJobJQ3']; $userName = $_POST['userName']; $accountNum = $_POST['accountNum']; $strHtm = "<br/>Output From AJAX Post Call.<br/>"; $strHtm .= "hidVal1: ". $hidVal1 ."<br/>"; $strHtm .= "hidVal2: ". $hidVal2 ."<br/>"; $strHtm .= "hidVal3: ". $hidVal3 ."<br/>"; $strHtm .= "Name: ". $name ."<br/>"; $strHtm .= "Occupation: ". $occupation ."<br/>"; $strHtm .= "userName: ". $userName ."<br/>"; $strHtm .= "accountNum: ". $accountNum ."<br/>"; echo $strHtm; ?>
jQuery AJAX - POST (FormData)Response
HTML
<form id="formJQ4"> <input type="hidden" name="hidValJQ4_1" id="hidValJQ4_1" value="1664"/> <input type="hidden" name="hidValJQ4_2" id="hidValJQ4_2" value="This is some text"/> <input type="hidden" name="hidValJQ4_3" id="hidValJQ4_3" value="199.99"/> <table> <tbody> <tr> <th>Name</th> <td> <input name="txtNameJQ4" id="txtNameJQ4" type="text" value="John" /> </td> </tr> <tr> <th>Occupation</th> <td> <input name="txtJobJQ4" id="txtJobJQ4" type="text" value="Software Developer" /> </td> </tr> </tbody> </table> </form> <a href="javascript:jQueryAjaxPost4()" class="btn btn-bs-primary">jQuery AJAX - POST (Serialize)</a> <br/> <br/> <h3>Response</h3> <div class="response" id="results11"></div>
jQuery
function jQueryAjaxPost4() { // PACKAGE THE SENDING DATA var form_str = $("#formJQ4").serialize(); var add_form = encodeURI("&userName=Paul McCartney&accountNum=352316"); form_str += add_form; $.ajax({ method: "POST", url: "AjaxResponse11.php", data: form_str, }) .done(function(msg){ ProcessResponse11(msg); }) } function ProcessResponse11(respText) { var divResult = document.getElementById("results11"); divResult.innerHTML = respText; }
Server Side PHP
<?php // GET POST VALUES $hidVal1 = $_POST['hidValJQ4_1']; $hidVal2 = $_POST['hidValJQ4_2']; $hidVal3 = $_POST['hidValJQ4_3']; $name = $_POST['txtNameJQ4']; $occupation = $_POST['txtJobJQ4']; $userName = $_POST['userName']; $accountNum = $_POST['accountNum']; $strHtm = "<br/>Output From AJAX Post Call.<br/>"; $strHtm .= "hidVal1: ". $hidVal1 ."<br/>"; $strHtm .= "hidVal2: ". $hidVal2 ."<br/>"; $strHtm .= "hidVal3: ". $hidVal3 ."<br/>"; $strHtm .= "Name: ". $name ."<br/>"; $strHtm .= "Occupation: ". $occupation ."<br/>"; $strHtm .= "userName: ". $userName ."<br/>"; $strHtm .= "accountNum: ". $accountNum ."<br/>"; echo $strHtm; ?>
jQuery AJAX - POST (Serialize)Response
HTML
<a href="javascript:standardAjaxXml1()" class="btn btn-bs-primary">Standard JS AJAX XML POST</a> <h3>Response</h3> <div class="response" id="results12"></div>
Javascript
function standardAjaxXml1() { // PACKAGE THE SENDING DATA AS XML var xmldata = "<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"+ "<Items>"+ "<Item>"+ "<hidVal1>John Lennon</hidVal1>"+ "<hidVal2>Vocals</hidVal2>"+ "</Item>"+ "<Item>"+ "<hidVal1>Ringo Starr</hidVal1>"+ "<hidVal2>Drums</hidVal2>"+ "</Item>"+ "</Items>"; var data = "xml_val="+ xmldata; // CREATE AN XML HTTP OBJECT if (window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest();}// For IE7+, ALL else {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} // For IE6-5 xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { ProcessResponse12(xmlhttp.responseText); } } xmlhttp.open("POST","AjaxResponse12.php",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send(data); } function ProcessResponse12(respText) { var divResult = document.getElementById("results12"); divResult.innerHTML = respText; }
Server Side PHP
<?php // AJAX RESPONSE SCRIPT $xmldata=$_POST['xml_val']; $parser=xml_parser_create(); xml_parse_into_struct($parser,$xmldata,$values); $count = count($values); $rtn_str='Values Returned: $count = '. $count .'<br/>'; for ($i=0; $i<$count; $i++) { $inner_ar = $values[$i]; $count_inner = count($inner_ar); $rtn_str .= 'Count Inner Array: '. $count_inner .', '; $rtn_str .= 'Type: '. gettype($values[$i]) .', '; $rtn_str .= 'Inner Ar Type: '. gettype($inner_ar) .'<br/>'; foreach ($inner_ar as $ar_value) { $rtn_str .= 'Inner-Inner Type: '. $ar_value .'<br/>'; } } $rtn_str .= '<br/>Values:<br/>'; $xml_data = simplexml_load_string($xmldata) or die("Error: Cannot create object"); foreach($xml_data->children() as $Item) { $rtn_str .= 'Item: '. $Item->hidVal1 . " - " . $Item->hidVal2 . "<br/>"; } echo $rtn_str; ?>
Standard JS AJAX XML POST