1 / 34

jQuery Ajax Json

jQuery Ajax Json. Using Jquery with PHP. Web Remoting. Web Remoting is a term used to categorize the technique of using JavaScript to directly make an HTTP request to the server and process the response.

slone
Download Presentation

jQuery Ajax Json

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. jQuery Ajax Json Using Jquery with PHP

  2. Web Remoting • Web Remoting is a term used to categorize the technique of using JavaScript to directly make an HTTP request to the server and process the response. • Traditionally, Web browsers initiate HTTP requests, not scripts. The classical function of a Web browser is based on a synchronous request/response model where HTTP requests are made in response to the user clicking links, submitting a form, or typing in a URL. • The browser processes the request by discarding the current page (including any running scripts), downloading a new page from the server, and then loading the new page in the browser for the user to view.

  3. Web Browser User submits form user waits… user waits… <html> <html> Web Server Process request User clicks link User enters URL Process request • This is a time-consuming process, especially when you don’t need to display a whole new page. • Often you only need to send a small amount of information to the server, or update a portion of the current page with a little data from the server.

  4. Ajax in jQuery • Functions • .load(): load remote file and insert into DOM • .get(): load remote page with HTTP GET request • .post(): load remote page with HTTP POST request • .ajax(): load a page using an HTTP request • Events: • ajaxComplete(), ajaxError(), ajaxStart(), ajaxSuccess()…

  5. The load() method • the load() method is a powerful method for loading data asynchronously. • Select an element on a page where you want the data loaded to and then call the load() method on it. • It takes the URL that you wish to load, as a parameter. • The load method can take two extra parameters: A set of querystring key/value pairs, and a callback function which will be executed when the load method finishes, no matter if it succeeds or fails.

  6. The load() method syntax: JQuery provides the load() method, an easy way to load any static or dynamic data: Syntax: [selector].load( URL, [data], [callback] ); Parameters: • URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database. • data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used. • callback: A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code.

  7. Example of the load() method: • An external file that we can load - content.html: <div id="divContent"> <b>This is external content</b> </div> <p>More content goes here.</p> • Load it – load_content.html: <div id="divTestArea1"> </div> <script type="text/javascript"> $(function() { $("#divTestArea1").load("content.html"); }); </script> http://www.jquery-tutorial.net/ajax/the-load-method/

  8. Example of the load() method: • You can pass a selector along with the URL, to only get a part of a page. • In the first example, we loaded the entire file, but in the following example, we will only use the div, which contains the first sentence – load_content2.html: <div id="divTestArea2"></div> <script type="text/javascript"> $(function() { $("#divTestArea2").load("content.html #divContent"); }); </script> • Simply append a standard jQuery selector to the parameter, after the URL, separated with a space. • This causes jQuery to select the content out and only pass the matched part(s) back to the container. • You can use any jQuery selector type to do this. http://www.jquery-tutorial.net/ajax/the-load-method/

  9. Example of the load() method: the callback function • Normally, you would likely only show a message if the method fails, to make sure the example fails request a file which doesn't exist – load_content3.html: <div id="divTestArea3"></div> <script type="text/javascript"> $(function() { $("#divTestArea3").load("no-content.html", function(responseText, statusText, xhr) { if(statusText == "success") alert("Successfully loaded the content!"); if(statusText == "error") alert("An error occurred: " + xhr.status + " - " + xhr.statusText); }); }); </script> • the callback function specifies 3 parameters, which jQuery will fill in for you. • The first parameter will contain the resulting content if the call succeeds. • The second parameter is a string which specifies the status of the call, e.g. "success" or "error". You can use it to see if the call was successful or not. • The third parameter is the XMLHttpRequest object used to perform the AJAX call. - It will contain properties which you can use to see what went wrong and many other things. http://www.jquery-tutorial.net/ajax/the-load-method/

  10. The get() and post() methods • The jQuery get() and post() methods allow you to easily send a HTTP request to a page and get the result back. • When you post a form, it's usually either a GET or a POST request, and with jQuery you can mimic that, since both a get() and a post() method exists. • The get() and post() methods take a single parameter, which is the URL that you wish to request. However, in most cases you will want to do something with the returned data. You can pass a callbackfunction as a parameter, which jQuery will call if the request succeeds. • Typically the reason for using a GET or a POST request is to pass in data values as parameters, which are processed by the server, for instance, with a piece of PHP, ASP or ASP.NET code, and then returned as a result. JQuery can take a map of GET or POST parameters. http://www.jquery-tutorial.net/ajax/the-get-and-post-methods/

  11. The get() method syntax: The jQuery.get( url, [data], [callback], [type] ) method loads data from the server using a GET HTTP request. The method returns an XMLHttpRequest object. Syntax: $.get( url, [data], [callback], [type] ) Parameters: • url: A string containing the URL to which the request is sent • data:: This optional parameter represents key/value pairs that will be sent to the server. • callback:: This optional parameter represents a function to be executed whenever the data is loaded successfully. • type:: This optional parameter represents type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".

  12. Example of the get() method: <script type="text/javascript"> $(function() { $.get("content.html", function(data, textStatus) { alert("Done, with the following status: " + textStatus + ". Here is the response: " + data); }); }); </script> • The first parameter is the URL • The second parameter is a callback function, which jQuery calls if the page request succeeds. Jquery_get_example.html http://www.jquery-tutorial.net/ajax/the-get-and-post-methods/

  13. The post() method syntax: The jQuery.post( url, [data], [callback], [type] ) method loads a page from the server using a POST HTTP request. The method returns XMLHttpRequest object. Syntax: $.post( url, [data], [callback], [type] ) Parameters: • url: A string containing the URL to which the request is sent • data:: This optional parameter represents key/value pairs or the return value of the .serialize() function that will be sent to the server. • callback:: This optional parameter represents a function to be executed whenever the data is loaded successfully. • type:: This optional parameter represents a type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".

  14. Example of the post() method: <script type="text/javascript"> $(function() { $.post("test_post.php", { name: "John Doe", age: "42" }, function(data, textStatus) { alert("Response from server: " + data); }); }); </script> • The first parameter is the URL • The second parameter passes in a data map of POST parameters. • The map is constructed of two parameters, a name and an age. If we had used a GET request instead of a POST request (POST requests doesn't take parameters from the URL like GET does), the above code would actually have corresponded to requesting a URL like this in your browser: test_get.php?name=John Doe&age=42 • The PHP script can then read the parameters, process them and return a result. jquery_post_example.html http://www.jquery-tutorial.net/ajax/the-get-and-post-methods/

  15. Example of the post() method: <html> <head> <title>the title</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("#driver").click(function(event){ $.post( "result.php", { name: "Zara" }, function(data) { $('#stage').html(data); } ); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id="stage" style="background-color:blue;"> STAGE </div> <input type="button" id="driver" value="Load Data" /> </body> </html> <?php if( $_REQUEST['name'] ) { $name = $_REQUEST['name']; echo "Welcome ". $name; } ?> jquery_post_example2.html and sender.html

  16. Ajax Examples • jQuery’s Ajax implementation • One of the most powerful jQuery functions is the Ajax function. The function provides enough options to make your XMLHttpRequest flexible enough to define: • What type of response you need to handle in your Ajax application (XML, JSON, HTML, script or text) • An option about what the script needs to do before the request is sent (validations, set a pre-loading image, etc.) • What to do after the request and response are successful • And options like the request URL (i.e. your PHP script), the time-out value and more. Check the jQuery page for all available options.

  17. The ajax() method syntax: The jQuery.ajax( options ) method loads a remote page using an HTTP request. $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually. Syntax: $.ajax( options ) Parameters: • options: A set of key/value pairs that configure the Ajax request. All options are optional. The next figure is a list of option which could be used as key/value pairs. Except for URL, the rest of the options are optional

  18. example of the ajax() method: • Browser-independent ajax queries: $.ajax({ type: "POST", url: "travel.php", data: "name=John&location=Boston", success: function(msg){ alert("Travel Interests Saved: " + msg ); } });   jquery_ajax_example.html

  19. jQuery, Ajax, Json and Php JavaScript Object Notation(JSON)is a popular way to send and receive data between browser and server. JSONis a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in JavaScript without issues. jQuery1.4 and above uses native JSON parsing JSON is an extremely lightweight, human-readable and highly compacted data-interchange format. JSON works on the principle of name/value pairing, and it’s very easy to read, write and parse. JSON is very useful when you want to pass data from one platform to any other platform - JSONPor "JSON with padding“ http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php

  20. jQuery, Ajax, Json and Php Consider xml-structure as below. <data> <sales> <item> <firstname>John</firstname> <lastname>Brown</lastname> </item> <item> <firstname>Marc</firstname> <lastname>Johnson</lastname> </item> </sales> </data> The question is ‘How does this structure translate to JSON/Javascript?’: var data ={ "sales":[ {"firstname":"John","lastname":"Brown"}, {"firstname":"Marc","lastname":"Johnson"} ]// end of sales array } As shown this is a name-value type syntax with colons in between. The rectangular brackets define the array, the curly brackets define the start and the end of JSON objects. http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php

  21. jQuery, Ajax, Json and Php The sales object can be accessed as follows: alert("first item: "+employees.sales[0]) varextraSales={"firstname":"Mary","lastname":"Doe"}; data.sales[employees.sales.length]=extraSales;// add extra sales record above (with index 2) to sales alert("extra sales from: "+data.sales[2].firstname);// shows "Mary" The JSON records are accessed using an index starting from zero. Furthermore a JSON substructure must be created first before its subfields can be accessed or set. For example: data.sales[3]=extraSales;// or: data.sales.push(extraSales); // the next statement is ok because sales[3] is has been created before data.sales[3].firstname="Pete"; • It is easy to pass JSON objects between jQuery and PHP http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php

  22. jQuery, Ajax, Json and Php <script type="text/javascript"> <!--$(document).ready(function(){ vardata = { "sales": [ { "firstname" : "John", "lastname" : "Brown" }, { "firstname" : "Marc", "lastname" : "Johnson" } ] // end of sales array } vardataString = JSON.stringify(data); $.post('simpleformSubmit.php', { data: dataString}, showResult, "text"); }); function showResult(res){ $("#fullresponse").html("Full response: " +res); varobj = JSON.parse(res); $("#sales1Lastname").html("Lastname of sales[1]: " +obj.sales[1].lastname);} //--> </script> <?php $logFile = 'logFile'; $res = json_decode(stripslashes($_POST['data']), true); error_log("result: ".$_POST['data'].", res=".json_encode($res), 3, $logFile); error_log(", sales1_lastname: ".$res['sales'][1]['lastname'], 3, $logFile); error_log("\n", 3, $logFile); header("Content-type: text/plain"); echo json_encode($res); ?> A JSON parser will recognize only JSON text, rejecting all scripts. varmyObject = JSON.parse(myJSONtext, reviver); A JSON stringifier converts JavaScript data structures into JSON text. varmyJSONText = JSON.stringify(myObject, replacer); http://www.json.org/js.html

  23. The getJSON() method syntax: If the server returns a response as a JSON string against your request, you can use the JQuery utility function getJSON() to parse the returned JSON string and make it available to the callback function as the first parameter, to take further action. Syntax: [selector].getJSON( URL, [data], [callback] ); Parameters: • URL: The URL of the server-side resource contacted via the GET method. • data: An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. • callback: A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second. This is a shorthand Ajax function, which is equivalent to: $.ajax({ url: url, dataType: 'json', data: data, success: callback });

  24. Support for JSON in PHP • Bundled into PHP 5.2.0+ by default • JSON functions • json_decode — Decodes a JSON string • json_encode — Returns the JSON representation of a value • json_last_error — Returns the last error occured

  25. json_decode() mixed json_decode ( string $json , bool $assoc) • Takes a JSON encoded string and converts it into a PHP value. • $json • The JSON string being decoded • $assoc • false (default)  return the value as an object • true  return the value as an associative array

  26. <?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); ?> object(stdClass)#1 (3) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) } array(3) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) } json_decode: Example #1 <?php $json = '{"foo-bar": 12345}'; $obj = json_decode($json); print $obj->{'foo-bar'}; // 12345 ?> json_decode: Example #2 http://www.php.net/manual/en/function.json-decode.php

  27. <?php // the following strings are valid JavaScript but not valid JSON // the name and value must be enclosed in double quotes // single quotes are not valid $bad_json = "{ 'bar': 'baz' }"; json_decode($bad_json); // null // the name must be enclosed in double quotes $bad_json = '{ bar: "baz" }'; json_decode($bad_json); // null // trailing commas are not allowed $bad_json = '{ bar: "baz", }'; json_decode($bad_json); // null // json_last_error() only works in PHP5.3+ json_decode: Example #3

  28.    switch (json_last_error()) {        case JSON_ERROR_NONE:            echo ' - No errors';        break;        case JSON_ERROR_DEPTH:            echo ' - Maximum stack depth exceeded';        break;        case JSON_ERROR_STATE_MISMATCH:            echo ' - Underflow or the modes mismatch';        break;        case JSON_ERROR_CTRL_CHAR:            echo ' - Unexpected control character found';        break;        case JSON_ERROR_SYNTAX:            echo ' - Syntax error, malformed JSON';        break;        case JSON_ERROR_UTF8:            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';        break;        default:            echo ' - Unknown error';        break;    }    echo PHP_EOL;   switch (json_last_error()) {        case JSON_ERROR_NONE:            echo ' - No errors';        break;        case JSON_ERROR_DEPTH:            echo ' - Maximum stack depth exceeded';        break;        case JSON_ERROR_STATE_MISMATCH:            echo ' - Underflow or the modes mismatch';        break;        case JSON_ERROR_CTRL_CHAR:            echo ' - Unexpected control character found';        break;        case JSON_ERROR_SYNTAX:            echo ' - Syntax error, malformed JSON';        break;        case JSON_ERROR_UTF8:            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';        break;        default:            echo ' - Unknown error';        break;    }    echo PHP_EOL; ?> json_decode: Example #3

  29. json_encode() string json_encode ( mixed $value ) • Returns a string containing the JSON representation of $value. • $value • The value being encoded. Can be any type except a resource. • This function only works with UTF-8 encoded data.

  30. <?php $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); // Output {"a":1,"b":2,"c":3,"d":4,"e":5} $arr = array ( 1, 2, 3, 4, 5 ); echo json_encode($arr); // Output [1,2,3,4,5] $arr['x'] = 10; echo json_encode($arr); // Output {"0":1,"1":2,"2":3,"3":4,"4":5,"x":10} echo json_encode(54321); // Output 54321 ?> json_encode: Example #1 http://www.php.net/manual/en/function.json-encode.php

  31. Links • http://arstechnica.com/business/news/2012/01/native-json-features-submitted-for-postgresql-92.ars • http://webhole.net/2009/12/16/how-to-read-xml-with-javascript/ • http://webhole.net/2009/11/28/how-to-read-json-with-javascript/ • http://webhole.net/2010/02/12/generate-json-with-php-and-read-it-with-jquery/ • http://youhack.me/2010/04/13/auto-load-page-content-every-x-second-using-jquery/ • http://www.99points.info/2010/06/ajax-tutorial-how-to-create-ajax-search-using-php-jquery-and-mysql/ • http://www.99points.info/2011/01/ajax-pagination-using-jquery-and-php-with-animation/ • http://www.99points.info/2010/07/youtube-style-ratingvoting-system-using-jquery-ajax-and-php-ever-best-tutorial/

  32. References • JSON • http://json.org/ • PHP Manual: JavaScript Object Notation • http://www.php.net/json • Speeding Up AJAX with JSON • http://www.developer.com/lang/jscript/article.php/3596836

More Related