Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com AJAX (Asynchronous Javascript And XML)  AJAX is the use of the XMLHttpRequest object to communicate with servers.  It can send and receive information in various formats, including JSON, XML, HTML and text files.  The two major features of AJAX allow you to do the following: o make requests to the server without reloading the page o receive and work with data from the server  It enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest class: Properties Methods readyState -- returns the state of the request 0 -> UNSENT [open() not called yet] 1 -> OPENED [open() has been called] 2 -> HEADERS_RECEIVED [send() has been called] 3 -> LOADING [responseText holds partial data] 4 -> DONE [the Operation is complete] setRequestHeader(header, value) --sets the value of an HTTP request header, must call it after open() but before send() methods getResponseHeader(header) --returns the string containing the text of a particular header’s value onreadystatechange -- an eventhandler that is called whenever the readyState attribute changes open(method, url) --initializes a request status --returns the numerical HTTP status code of the XMLHttpRequest’s response send(req_body) – req_body is optional --sends the request to the server responseType --the type of the data contained in the response “” -> text (default) json -> json object document -> HTML document blob -> blob object containing the binary data abort() --aborts the request if it has already been sent responseText --contains response to the request as text or null if the request was unsuccessful Events: abort, error, load, loadend, loadstart, progress, timeout response --returns the reponse’s body content as a document, text, JSON, blob depending on the value of the request’s reponseType property. Sending GET Request: <button id="ajaxButton" type="button">Make a request</button> <script> (function() { var httpRequest; document.getElementById("ajaxButton").addEventListener('click', makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance');
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com return false; } httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', 'test.html'); httpRequest.send(); } function alertContents() { try { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } catch( e ) { alert('Caught Exception: ' + e.description); } } })(); </script> Sending POST request: <script> function makeRequest(url, userName) { … … … httpRequest.onreadystatechange = alertContents; httpRequest.open('POST', url); httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); httpRequest.send('userName=' + encodeURIComponent(userName)); } </script>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com JSON (Javascript Object Notation) When exchanging data between a browser and a server, the data can only be text. JSON is text that is used to transmit structured data over network connection. Format: 1. JSON objects are surrounded by curly braces {} 2. JSON objects are written in key/value pairs 3. Keys must be double quoted strings 4. Values can be null, true, false, JSONNumber, JSONString, JSONObject, JOSNArray 5. Keys and values are separated by a colon 6. Each key/value pair is separated by a comma For example, var myobj = { “name” : ”John”, “age” : “30”, “cars” : [ { “name” : ”Ford”, “models”: [“fiesta”,”focus”,”mustang”] }, { “name”:”BMW”, “models”:[“320”,”x3”,”x5”] }, { “name”:”Fiat”, “models”:[“500”,”Panda”] } ] }; JSON Methods: Javascript PHP JSON.stringify()  converts a JavaScript object or value to a JSON string. console.log(JSON.stringify({ x: 5, y: 6 })); // expected output: ‘{"x":5,"y":6}’ json_encode() — Returns the JSON representation of a value <?php $arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4, 'e'=>5); echo json_encode($arr); ?> JSON.parse()  parses a JSON string, constructs the JavaScript value or object described by the string. var json = '{"result":true, "count":42}'; obj = JSON.parse(json); console.log(obj.count); // expected output: 42 json_decode() -- takes a JSON encoded string and converts it into a PHP variable. <?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5 }';
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com var_dump(json_decode($json, true)); //assoc array ?> encodeURIComponent(str) -- encodes a Uniform Resource Identifier (URI) component. <script> var set1 = ";,/?:@&=+$#"; // Reserved Characters var set2 = "-_.!~*'()"; // Unreserved Marks var set3 = "ABC abc 123"; // Alphanumeric Characters + Space console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // - _.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20) </script> decodeURIComponent(encodedString) – decodes the encoded URI. PHP Network Functions: Method Sample Code header ($headerstring) – send a raw HTTP header The header() must be called before any actual output is sent either by normal HTML tags, blank lines in a file or from PHP. header_remove($name) – removes a previously set header. <html> <?php /* This will give an error. Note the output * above, which is before the header() call */ header('Location: http://www.example.com/'); /* Make sure that code below does not get * executed when we redirect */ exit; ?> http_response_code() http_response_code(codenumber) — Gets or Sets the HTTP response code <?php // Get the current default response code var_dump(http_response_code()); // Set a response code var_dump(http_response_code(201)); // Get the new response code var_dump(http_response_code()); ?>

Web 11 | AJAX + JSON + PHP

  • 1.
    Mohammad Imam Hossain,Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com AJAX (Asynchronous Javascript And XML)  AJAX is the use of the XMLHttpRequest object to communicate with servers.  It can send and receive information in various formats, including JSON, XML, HTML and text files.  The two major features of AJAX allow you to do the following: o make requests to the server without reloading the page o receive and work with data from the server  It enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest class: Properties Methods readyState -- returns the state of the request 0 -> UNSENT [open() not called yet] 1 -> OPENED [open() has been called] 2 -> HEADERS_RECEIVED [send() has been called] 3 -> LOADING [responseText holds partial data] 4 -> DONE [the Operation is complete] setRequestHeader(header, value) --sets the value of an HTTP request header, must call it after open() but before send() methods getResponseHeader(header) --returns the string containing the text of a particular header’s value onreadystatechange -- an eventhandler that is called whenever the readyState attribute changes open(method, url) --initializes a request status --returns the numerical HTTP status code of the XMLHttpRequest’s response send(req_body) – req_body is optional --sends the request to the server responseType --the type of the data contained in the response “” -> text (default) json -> json object document -> HTML document blob -> blob object containing the binary data abort() --aborts the request if it has already been sent responseText --contains response to the request as text or null if the request was unsuccessful Events: abort, error, load, loadend, loadstart, progress, timeout response --returns the reponse’s body content as a document, text, JSON, blob depending on the value of the request’s reponseType property. Sending GET Request: <button id="ajaxButton" type="button">Make a request</button> <script> (function() { var httpRequest; document.getElementById("ajaxButton").addEventListener('click', makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance');
  • 2.
    Mohammad Imam Hossain,Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com return false; } httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', 'test.html'); httpRequest.send(); } function alertContents() { try { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } catch( e ) { alert('Caught Exception: ' + e.description); } } })(); </script> Sending POST request: <script> function makeRequest(url, userName) { … … … httpRequest.onreadystatechange = alertContents; httpRequest.open('POST', url); httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); httpRequest.send('userName=' + encodeURIComponent(userName)); } </script>
  • 3.
    Mohammad Imam Hossain,Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com JSON (Javascript Object Notation) When exchanging data between a browser and a server, the data can only be text. JSON is text that is used to transmit structured data over network connection. Format: 1. JSON objects are surrounded by curly braces {} 2. JSON objects are written in key/value pairs 3. Keys must be double quoted strings 4. Values can be null, true, false, JSONNumber, JSONString, JSONObject, JOSNArray 5. Keys and values are separated by a colon 6. Each key/value pair is separated by a comma For example, var myobj = { “name” : ”John”, “age” : “30”, “cars” : [ { “name” : ”Ford”, “models”: [“fiesta”,”focus”,”mustang”] }, { “name”:”BMW”, “models”:[“320”,”x3”,”x5”] }, { “name”:”Fiat”, “models”:[“500”,”Panda”] } ] }; JSON Methods: Javascript PHP JSON.stringify()  converts a JavaScript object or value to a JSON string. console.log(JSON.stringify({ x: 5, y: 6 })); // expected output: ‘{"x":5,"y":6}’ json_encode() — Returns the JSON representation of a value <?php $arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4, 'e'=>5); echo json_encode($arr); ?> JSON.parse()  parses a JSON string, constructs the JavaScript value or object described by the string. var json = '{"result":true, "count":42}'; obj = JSON.parse(json); console.log(obj.count); // expected output: 42 json_decode() -- takes a JSON encoded string and converts it into a PHP variable. <?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5 }';
  • 4.
    Mohammad Imam Hossain,Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com var_dump(json_decode($json, true)); //assoc array ?> encodeURIComponent(str) -- encodes a Uniform Resource Identifier (URI) component. <script> var set1 = ";,/?:@&=+$#"; // Reserved Characters var set2 = "-_.!~*'()"; // Unreserved Marks var set3 = "ABC abc 123"; // Alphanumeric Characters + Space console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // - _.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20) </script> decodeURIComponent(encodedString) – decodes the encoded URI. PHP Network Functions: Method Sample Code header ($headerstring) – send a raw HTTP header The header() must be called before any actual output is sent either by normal HTML tags, blank lines in a file or from PHP. header_remove($name) – removes a previously set header. <html> <?php /* This will give an error. Note the output * above, which is before the header() call */ header('Location: http://www.example.com/'); /* Make sure that code below does not get * executed when we redirect */ exit; ?> http_response_code() http_response_code(codenumber) — Gets or Sets the HTTP response code <?php // Get the current default response code var_dump(http_response_code()); // Set a response code var_dump(http_response_code(201)); // Get the new response code var_dump(http_response_code()); ?>