Ajax
Ajax Ajax = Asynchronous JavaScript and XML Using a set of methods built in to JavaScript to transfer data between the browser and a server in the background Reduces the amount of data that must be sent back Makes web pages seamlessly dynamic, the results are a much improved user interface and better responsiveness
Ajax 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
http://derivadow.com/2007/01/05/ajax-what-is-it-its-not-dhtml/
` http://imps.mcmaster.ca/courses/se-4c03-07/wiki/vanschj/vanschj_picture1.png
AJAX is Based on 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
Technologies userd in Ajax JavaSScript Loosely typed scripting language. JavaScript function is called when an event occurs in a page. Glue for the whole AJAX operation. DOM API for accessing and manipulating structured documents. Represents the structure of XML and HTML documents. CSS Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript. XMLHttpReques JavaScript object that performs asynchronous interaction with the server.
Examples Google Maps : A user can drag an entire map by using the mouse, rather than clicking on a button. Google Suggest : As you type, Google offers suggestions. Use the arrow keys to navigate the results http://maps.google.com/ http://www.google.com/webhp?complete=1&hl=en Gmail : Gmail is a webmail built on the idea that emails can be more intuitive, efficient, and useful. http://gmail.com/
Browser support A list of major browsers that support AJAX Mozilla Firefox 1.0 and above. Netscape version 7.1 and above. Apple Safari 1.2 and above. Microsoft Internet Explorer 5 and above. Konqueror. Opera 7.6 and above. Google Chrome
Using XMLHttpRequest Three ways of creating an XMLHttpRequest object IE 5: request = new ActiveXObject("Microsoft.XMLHTTP") IE 6+: request = new ActiveXObject("Msxml2.XMLHTTP") All others: request = new XMLHttpRequest()
A cross-browser Ajax function
A Ajax function
Steps of AJAX Operation 1. A client event occurs. 2. An XMLHttpRequest object is created. 3. The XMLHttpRequest object is configured. 4. The XMLHttpRequest object makes an asynchronous request to the Webserver. 5. The Webserver returns the result containing XML document. 6. The XMLHttpRequest object calls the callback() function and processes the result. 7. The HTML DOM is updated.
1.A Client Event Occurs A JavaScript function is called as the result of an event. Example: <input type="text" id="userid" name="id" onkeyup="validateuserid();"> validateuserid() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to "userid"
2.The XMLHttpRequest Object is Created
3.The XMLHttpRequest Object is Configured In this step, we will write a function that will be triggered by the client event and a callback function processrequest() will be registered
4.Making Asynchronous Request to the Webserver Assume you enter wittawas in the userid box, then in the above request, the URL is set to "validate?id=wittawas"
5.Webserver Returns the Result Containing XML Document You can implement your server-side script in any language, however its logic should be as follows. Get a request from the client. Parse the input from the client. Do required processing. Send the output to the client.
6.Callback Function processrequest() is Called XMLHttpRequest object was configured to call the processrequest() function when there is a state change to the readystate of the XMLHttpRequest object function will receive the result from the server and will do the required processing
7.The HTML DOM is Updated The final step, your HTML page will be updated, It happens in the following way: JavaScript gets a reference to any element in a page using DOM API. document.getelementbyid("useridmessage") JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements
cal.html Put it all together (only + operator) cal.php
cal.html (short version)
XMLHTTPREQUEST The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000 XMLHttpRequest (XHR) is an API that can be used by JavaScript, Jscript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side. The data returned from XMLHttpRequest calls will often be provided by back-enddatabases. XMLHttpRequest can be used to fetch data in XML or other formats, e.g. JSON or even plain text.
XMLHttpRequest Properties onreadystatechange : An event handler for an event that fires at every state change. readystate : The readystate property defines the current state of the XMLHttpRequest object.
readystate 0 : After you have created the XMLHttpRequest object, but before you have called the open() method. 1 : After you have called the open() method, but beforeyou have called send(). 2 : After you have called send(). 3 : After the browser has established a communication with the server, but before the server has completed the response. 4 : After the request has been completed, and the response data has been completely received from the server.
XMLHttpRequest Properties responsetext : Returns the response as a string. responsexml : Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties. status : Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK"). statustext : Returns the status as a string (e.g., "Not Found" or "OK").
XMLHttpRequest Methods abort() getallresponseheaders() Returns the value of the specified HTTP header. send( content ) Returns the complete set of HTTP headers as a string. getresponseheader( headername ) Cancels the current request. Sends the request. setrequestheader( label, value ) Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Methods open( method, URL ) open( method, URL, async ) open( method, URL, async, username ) open( method, URL, async, username, password ) The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods such as "PUT" and "DELETE" (primarily used in REST applications) may be possible. The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
Performing POST requests using Ajax GET is simpler and faster than POST, and can be used in most cases. Use POST requests when A cached file is not an option (update a file or database on the server) Sending a large amount of data to the server (POST has no size limitations) Sending user input (which can contain unknown characters) POST is more robust and secure than GET http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
GET request POST request parameters เหมม อน query string แตต ไมต ตต องมม? และตต องมม การสต ง content type เปป น "application/x-www-form-urlencoded" cal.php
Retrieving an XML document using Ajax Ajax can retrieve that well formed XML text file and return it back to you as a XML object This enables the XML data to be easily parsed using standard DOM methods.
cd_catalog.xml http://www.w3schools.com/ajax/cd_catalog.xml
Read more Reference Read more http://teamtreehouse.com/library/ajax-basics (vdo) http://www.w3schools.com/ajax/ http://www.tutorialspoint.com/ajax/ajax_tutorial.pdf
Questions?
JSON
What is JSON? JSON stands for JavaScript Object Notation. The format was specified by Douglas Crockford. It was designed for human-readable data interchange. It has been extended from the JavaScript scripting language. The filename extension is.json. JSON Internet Media type is application/json. The Uniform Type Identifier is public.json http://www.iana.org/assignments/media-types/media-types.xhtml https://en.wikipedia.org/wiki/json
Uses of JSON It is used while writing JavaScript based applications that includes browser extensions and websites. JSON format is used for serializing and transmitting structured data over network connection. It is primarily used to transmit data between a server and web applications. Web services and APIs use JSON format to provide public data. It can be used with modern programming languages.
Characteristics of JSON JSON is easy to read and write. It is a lightweight text-based interchange format. JSON is language independent.
Simple Example in JSON store information about books based on their topic and edition
A person described by JSON
JSON - Syntax Data is represented in name/value pairs. Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by, (comma). Square brackets hold arrays and values are separated by,(comma).
JSON supports two data structures Collection of name/value pairs This Data Structure is supported by different programming languages. Ordered list of values It includes array, list, vector or sequence etc.
JSON - DataTypes
Number It is a double precision floating-point format in JavaScript and it depends on implementation. Octal and hexadecimal formats are not used. No NaN or Infinity is used in Number. var obj = {marks: 97}
String It is a sequence of zero or more double quoted Unicode characters with backslash escaping. var obj = {name: Witty }
Boolean It includes true or false value. var obj = { } name: 'Amit', marks: 97, distinction: true
Array It is an ordered collection of values. These are enclosed in square brackets which means that array begins with [ and ends with ] The values are separated by, (comma). Array indexing can be started at 0 or 1. Arrays should be used when the key names are sequential integers.
Object It is an unordered set of name/value pairs. Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'. Each name is followed by ':'(colon) and the name/value pairs are separated by, (comma). The keys must be strings and should be different from each other. Objects should be used when the key names are arbitrary strings.
example Example object books that contain array of multiple objects
JSON - Objects JSON objects can be created with JavaScript. Creation of an empty Object var JSONObj = {}; Creation of a new Object var JSONObj = new Object(); Or Creation with name/value pairs var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 }
Example
Example
JSON - Comparison with XML Verbose XML is more verbose than JSON, so it is faster to write JSON for programmers. Arrays Usage XML is used to describe the structured data, which doesn't include arrays whereas JSON include arrays. Parsing JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.
Using JSON in JavaScript JSON.parse() turns a string of JSON text into an object. JSON.stringify() turns an object in to a JSON text and stores that JSON text in a string.
JSON with Ajax data.json
JSON with PHP
Encoding JSON in PHP
Decoding JSON in PHP
References http://www.tutorialspoint.com/json/json_quick_guide.htm https://en.wikipedia.org/wiki/json http://json-schema.org/ http://w3techs.com/
Questions?