JavaScript + PHP AJAX. Costantino Pistagna

Similar documents

AJAX เสถ ยร ห นตา ส าน กเทคโนโลย สารสนเทศและการส อสาร มหาว ทยาล ยนเรศวร พะเยา

An Introduction to AJAX. By : I. Moamin Abughazaleh

AJAX(Asynchronous Javascript + XML) Creating client-side dynamic Web pages

AJAX. Introduction. AJAX: Asynchronous JavaScript and XML


CITS1231 Web Technologies. Ajax and Web 2.0 Turning clunky website into interactive mashups

A.A. 2008/09. What is Ajax?

XMLHttpRequest. CS144: Web Applications

JSON. Dr. Kanda Runapongsa Saikaew Computer Engineering Department

AJAX. Ajax: Asynchronous JavaScript and XML *


Web Programming/Scripting: PHP and AJAX Refresher

A synchronous J avascript A nd X ml

AJAX and PHP AJAX. Christian Wenz,

AJAX: Introduction CISC 282 November 27, 2018

AJAX ASYNCHRONOUS JAVASCRIPT AND XML. Laura Farinetti - DAUIN

/ Introduction to XML

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains 2 components

So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

The Reactor Model: An Experiment in Declarative Concurrent Programming

First Version Web 1.0: customer.jsp

Contents. Demos folder: Demos\14-Ajax. 1. Overview of Ajax. 2. Using Ajax directly. 3. jquery and Ajax. 4. Consuming RESTful services

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains an Individual and Group component

2/6/2012. Rich Internet Applications. What is Ajax? Defining AJAX. Asynchronous JavaScript and XML Term coined in 2005 by Jesse James Garrett

AJAX: The Basics CISC 282 March 25, 2014

10.1 Overview of Ajax

AJAX: The Basics CISC 282 November 22, 2017

It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

CSC Web Technologies, Spring Web Data Exchange Formats

AJAX. Lecture 26. Robb T. Koether. Fri, Mar 21, Hampden-Sydney College. Robb T. Koether (Hampden-Sydney College) AJAX Fri, Mar 21, / 16

Session 11. Ajax. Reading & Reference

Ajax. Ronald J. Glotzbach

Use of PHP for DB Connection. Middle and Information Tier

Ajax- XMLHttpResponse. Returns a value such as ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, based on the value of

wemx WebService V1.0

AJAX Programming Chris Seddon

Client Side JavaScript and AJAX

Ajax Application Design

Web Application Security

Session 18. jquery - Ajax. Reference. Tutorials. jquery Methods. Session 18 jquery and Ajax 10/31/ Robert Kelly,

Introduction to JSON. Roger Lacroix MQ Technical Conference v

CSC 337. JavaScript Object Notation (JSON) Rick Mercer

ajax1.html 1/2 lectures/7/src/ ajax1.html 2/2 lectures/7/src/

User Interaction: jquery

Module7: AJAX. Click, wait, and refresh user interaction. Synchronous request/response communication model. Page-driven: Workflow is based on pages

Ajax. David Matuszek's presentation,

CENG 490 STARSOFT. Requirement Analysis Report


Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum


Fall Semester (081) Module7: AJAX

jquery and AJAX

JSON is a light-weight alternative to XML for data-interchange JSON = JavaScript Object Notation

Lesson 12: JavaScript and AJAX

TIME SCHEDULE MODULE TOPICS PERIODS. HTML Document Object Model (DOM) and javascript Object Notation (JSON)

CSE 130 Programming Language Principles & Paradigms Lecture # 20. Chapter 13 Concurrency. + AJAX Discussion

1 Explain the following in brief, with respect to usage of Ajax

Introduction to Ajax

Use of PHP for DB Connection. Middle and Information Tier. Middle and Information Tier

,

Advanced Web Programming with JavaScript and Google Maps. Voronezh State University Voronezh (Russia) AJAX. Sergio Luján Mora

JSON as an XML Alternative. JSON is a light-weight alternative to XML for datainterchange

CS 5142 Scripting Languages

Asynchronous JavaScript + XML (Ajax)

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

ASPFileSaver - File Upload Component

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity]

Part A Short Answer (50 marks)

Task 1. Set up Coursework/Examination Weights

Working with Database. Client-server sides AJAX JSON Data formats Working with JSON data Request Response Bytes Database

AJAX and JSON. Day 8

AJAX: Rich Internet Applications

COPYRIGHTED MATERIAL. AJAX Technologies. Google Suggest

Credits: Some of the slides are based on material adapted from

quiz 1 details wed nov 17, 1pm see handout for locations covers weeks 0 through 10, emphasis on 7 onward closed book bring a , 2-sided cheat she

Session 11. Calling Servlets from Ajax. Lecture Objectives. Understand servlet response formats

Introduction to AJAX Bringing Interactivity & Intuitiveness Into Web Applications. By : Bhanwar Gupta SD-Team-Member Jsoft Solutions

CSC 405 Computer Security. Web Security

Building Dynamic Forms with XML, XSLT

CSC Javascript

Pure JavaScript Client

EECS1012. Net-centric Introduction to Computing. Lecture "Putting It All Together" and a little bit of AJAX

CS50 Quiz Review. November 13, 2017

Introduction to Web Development

PHP Introduction. Some info on MySQL which we will cover in the next workshop...

XML JavaScript Object Notation JSON Cookies Miscellaneous What Javascript can t do. OOP Concepts of JS

Controller/server communication

SEEM4570 System Design and Implementation Lecture 03 JavaScript

Ajax or AJAX? The acronym AJAX has changed to the term Ajax, which does not represent specific technologies

Jquery Ajax Json Php Mysql Data Entry Example

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

Introduction to InfoSec SQLI & XSS (R10+11) Nir Krakowski (nirkrako at post.tau.ac.il) Itamar Gilad (itamargi at post.tau.ac.il)

AJAX. Lab. de Bases de Dados e Aplicações Web MIEIC, FEUP 2010/11. Sérgio Nunes

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 07 Minor Subject

Grading for Assignment #1

Creating an Online Catalogue Search for CD Collection with AJAX, XML, and PHP Using a Relational Database Server on WAMP/LAMP Server

Part of this connection identifies how the response can / should be provided to the client code via the use of a callback routine.

JavaScript Functions, Objects and Array

REST. Web-based APIs

Transcription:

JavaScript + PHP AJAX Costantino Pistagna <pistagna@dmi.unict.it>

What s is Ajax? AJAX is not a new programming language It s a new technique for better and faster web applications. JavaScript can communicate directly with the server. with the XMLHttpRequest object. JavaScript can trade data with webserver without reloading the page.

AJAX uses asynchronous data transfer HTTP requests between the browser and the web server Request small bits of information from the server instead of whole pages speed++ interaction AJAX makes Internet applications smaller, faster and more user-friendly. Ajax Technologies

AJAX is based on the following web standards: JavaScript XML / JSON HTML CSS AJAX Standards

The XMLHttpRequest object To get or send information from/to a server with traditional JavaScript Make an HTML form Click the "Submit" button to send/get the information Wait for the server to respond Then a new page will load with the results The server returns a new page each time the user submits input Traditional web applications can run slowly Tend to be less user-friendly

The XMLHttpRequest object With AJAX, your JavaScript communicates directly with the server, Through the JavaScript XMLHttpRequest object. XMLHttpRequest makes a request and get a response from server without reloading the page. The user will stay on the same page he will not notice that scripts request pages data to server in background. Introduces some things that were otherwise impossible HEAD requests

Instead of a user request being made to server via HTTP POST or GET request such as would be made by submitting a form An Ajax script makes a request to the server by using the Javascript XMLHTTPRequest object This object may be unfamiliar to many it behaves like a fairly ordinary javascript object! How does it work?

How does it work? When using a javascript image object... We may dynamically change the URL of the image source Without using a page refresh. XMLHTTPRequest retrieves information from the server in a similarly invisible manner.

Why XML HTTP Request object? Whilst the object is called the XML HTTP Request object it is not limited to being used with XML it can request or send any type of document Dealing with binary streams can be problematical in javascript. we will see the JSON alternative

Ajax Events Ajax uses a programming model with display and events These events are user actions they call functions associated to elements of the web page Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server.

XMLHttpRequest Methods To get data on the server, XMLHttpRequest provides two methods: - open: create a connection. - send: send a request to the server. Data by the server will be found in the attributes of the XMLHttpRequest object: - responsexml for an XML file or - responsetext!for a plain text. Take note that a new XMLHttpRequest object has to be created for each new file to load. We have to wait for the data to be available to process it The state of availability of data is given by the readystate attribute of XMLHttpRequest.

How is it coded? We need to know how to create an XMLHTTPRequest object.! The process differs slightly if you are using Internet Explorer (5+)!with ActiveX enabled or a standards-compliant browser such as Mozilla Firefox. With IE, the request looks like: http = new ActiveXObject("Microsoft.XMLHTTP"); In a standards browser we can instantiate the object directly: http = new XMLHttpRequest();

Our Implementation function gethttpobject() { if (typeof XMLHttpRequest!= 'undefined') { return new XMLHttpRequest(); try { return new ActiveXObject("Msxml2.XMLHTTP"); catch (e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); catch (e) { return false;

Our Implementation We need to write an event handler which will be called via some event on our user's page Will handle sending our request for data to our server The event handler will use methods of XMLHTTPRequest object: Make the request of the server Check when the server has completed the request Deal with the information returned by the server

Our Implementation For example, We can make our request of the server by using a GET method to an appropriate server-side script.! Assuming that we have created our XMLHTTPRequest object and called it!http: var http = gethttpobject(); http.open("get", "http://example.org/test.txt", true); http.onreadystatechange = function() {! if (http.readystate == 4) {!! dosomethingwith(http.responsetext);! http.send(null);

Our Implementation The function listens to the onreadystatechange property each time this parameter changes calls a further function We said little about the server-side script which is called Essentially this can be any server routine which will generate the required output when called with the relevant URL and appended parameters as in any other HTTP GET request.!

Handling data: readystate We need to write a function usehttpresponse will establish when the server has completed our request and do something useful with the data it has returned: function usehttpresponse() { " if (http.readystate == 4) { """ var textout = http.responsetext; """ document.write.textout; "

Handling data: readystate Our function checks for a readystate value of 4 there are various numbered states describing the progress of such a request tipically, we are interested in the value of 4 which indicates that the request is complete and we can use the returned data. 0: not initialized. 1: connection established. 2: request received. 3: answer in process. 4: finished.

responsetext var textout = http.responsetext; We have received our information as simple text via the responsetext property of our XMLHTTPRequest object Information can be returned as XML or as properties of a predefined javascript object

Example: Get a text <html><head><script> function submitform(){ var http; try { http = new ActiveXObject('Msxml2.XMLHTTP'); catch (e) { try { http = new ActiveXObject('Microsoft.XMLHTTP'); catch (e2) { try { http = new XMLHttpRequest(); catch (e3) { http = false; http.onreadystatechange = function() { if(http.readystate == 4) { if(http.status == 200) document.ajax.dyn="received:" + http.responsetext; else document.ajax.dyn="error code " + http.status; ; ""http.open(get, "data.txt", true); http.send(null); </script></head> <body> <FORM method="post" name="ajax" action=""> <INPUT type="button" value="submit" ONCLICK="submitForm()"> "<INPUT type="text" name="dyn" value=""> </FORM> </body></html>

Get from XML To get data from an XML file, we have just to replace this line: document.ajax.dyn="received:" + http.responsetext; by this code: // Assign the XML file to a var var doc = http.responsexml; // Read the first element var element = doc.getelementsbytagname('root').item(0); // Assign the content to form document.ajax.dyn.value= element.firstchild.data;

Write to body In this demo, the text read is put into the body of the page not into a textfield The code below replaces the textfield form object <div id="zone"> "... some text to replace... </div> the second part replaces the assignment into the JavaScript function. document.getelementbyid("zone").innerhtml = "Received:" + http.responsetext;

Post a text In this demo, a text is sent to the server and is written into a file. The call to the "open" method changes the argument is POST the url is the name of a file or script that receives the data sent the "send" method has now a value as argument that is a string of parameters. http.open("post", "ajax-post-text.php", true); http.setrequestheader("content-type", "application/x-www-form-urlencoded"); http.send(data);

Post a text The parameter of the send method is in the format of the HTML POST method. When several values are sent, they are separated by the ampersand symbol: var data = "file=" + url + "&content=" + content;

A sample and full application - Step #1 Creating the form We first create a simple webpage that has the HTML for our Web form. There is nothing out of the ordinary here - just basic HTML defining the city, state, and ZIP code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>zip Code to City and State using XmlHttpRequest</title> </head> <body> <form action="post"> <p> ZIP code: <input type="text" size="5" name="zip" id="zip" /> </p> City: <input type="text" name="city" id="city" /> State: <input type="text" size="2" name="state" id="state" /> </form> </body></html>

A sample and full application - Step #2 Add an onblur event handler function named updatecitystate() This event handler is called whenever the ZIP code field loses focus. onblur="updatecitystate();" The updatecitystate() function will be in charge of asking the server what the city and state is for a given Zip code. For now, this function does nothing.... <script language="javascript" type="text/javascript"> function updatecitystate() { /* does nothing...yet! */ </script> </head><body> <form action="post"> <p>zip code: <input type="text" size="5" name="zip" id="zip" onblur="updatecitystate();" />...

A sample and full application - Step #3 Of course we need to create an XMLHttpRequest object. function gethttpobject() { var xmlhttp; if (!xmlhttp && typeof XMLHttpRequest!= 'undefined') { try { xmlhttp = new XMLHttpRequest(); catch (e) { xmlhttp = false; return xmlhttp; var http = gethttpobject(); // We create the HTTP Object

A sample and full application - Step #4 Now add the code that makes the round trip to the server. We first specify the URL for the server-side script: getcitystate.php?param= This URL will then have the ZIP Code appended to it so that the ZIP code is passed as an HTTP GET parameter named param This means that if a user types in the ZIP code of 17534, the resulting URL would be getcitystate.php?param=17534. Before we send the HTTP request, we specify the onreadystatechange property The name of our new function handlehttpresponse(). This means that every time the HTTP ready state has changed, our function handlehttpresponse() is called.

A sample and full application - Step #4 Our new function handlehttpresponse() sits there waiting to be called and when it does get called, it check to see if the readstate is equal to 4. If it is equal to 4 this means that the request is complete. Since the request is complete, it is now fair game to grab the response text (responsetext) unpack it, set the city and state form fields to the returned values var url = "getcitystate.php?param="; // The server-side script function handlehttpresponse() { if (http.readystate == 4) { // Split the comma delimited response into an array results = http.responsetext.split(","); document.getelementbyid('city').value = results[0]; document.getelementbyid('state').value = results[1]; function updatecitystate() { var zipvalue = document.getelementbyid("zip").value; http.open("get", url + escape(zipvalue), true); http.onreadystatechange = handlehttpresponse; http.send(null);

A sample and full application - Step #5 Lets now create a PHP file named getcitystate.php All this file does is return Catania, Italy as the city and state. This means that anytime the focus leaves the ZIP code field The city and state will be automatically set to Catania, Itay... <?php echo "Catania, Italy";?>... @home: get results from a text file with the following format... CITY:STATE...

HTML Part: AJAX Suggest <form> First Name: <input type="text" id="txt1" onkeyup="showhint(this.value)"/> </form> <p>suggestions: <span id="txthint"></span> </p>

JavaScript Part: AJAX Suggest function showhint(str) { if (str.length==0) { " document.getelementbyid("txthint").innerhtml=""; " return; http=getxmlhttpobject(); if (http==null) { " alert ("Your browser does not support XMLHttpRequest!"); " return; var url="gethint.php"; url=url+"?q="+str; url=url+"&sid="+math.random(); http.onreadystatechange=statechanged; http.open("get",url,true); http.send(null);

JavaScript Part2: AJAX Suggest function statechanged() { if (http.readystate==4) { document.getelementbyid("txthint").innerhtml=http.responsetext; "

PHP Part: AJAX Suggest <?php // Fill up array with names $a[]="anna";$a[]="barbara";$a[]="cinzia";$a[]="diana";$a[]="elisa"; $//get the q parameter from URL $q=$_get["q"]; //lookup all hints from array if length of q>0 if (strlen($q) > 0) { $hint=""; for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))){ if ($hint==""){ $hint=$a[$i]; else { $hint=$hint.", ".$a[$i]; // Set output to "no suggestion" if no hint were found if ($hint == "") { $response="no suggestion"; else { $response=$hint; //output the response echo $response;?>

JSON: What does it stand for? JavaScript Object Notation JSON is a syntax for passing around objects that contain name/value pairs arrays other objects {"skillz": {! "web":[!! {"name": "html",!! "years": "5"!!,!! {"name": "css",!! "years": "3"!! ]! "database":[!! {"name": "sql",!! "years": "7"!! ]

Squiggles, Squares, Colons and Commas Squiggly brackets act as 'containers' Square brackets holds arrays Names and values are separated by a colon. Array elements are separated by commas Think 'XML with Anorexia'

JSON is like XML because: They are both 'self-describing' meaning that values are named, and thus 'human readable' Both are hierarchical. (i.e. You can have values within values.) Both can be parsed and used by lots of programming languages Both can be passed around using AJAX (i.e. httpwebrequest)

JSON is UNlike XML because: XML uses angle brackets, with a tag name at the start and end of an element: JSON uses squiggly brackets with the name only at the beginning of the element. JSON is less verbose so it's definitely quicker for humans to write, and probably quicker for us to read. JSON can be parsed trivially using the eval() procedure in JavaScript JSON includes arrays {where each element doesn't have a name of its own In XML you can use any name you want for an element, in JSON you can't use reserved words from javascript

Behold, an Object The Object: An Introduction var myfirstobject = {; The old way to create a new object was to use the new keyword. var myjson = new Object(); This method has been deprecated now in favor of simply defining an empty object with squigly braces. var myjson = {;

Objects as Data A Javascript Object is a very flexible and robust data format expressed as name/value pairs That is, an object holds a name which is an object's property Think of it as a plain old variable name that's attached to the object name. And the object holds the value of that name var myfirstjson = { "firstname" : "Mario", " " " " " " " " " " "lastname" ": "Rossi", " " " " " " " " " " "age" " " " : 23 ; document.writeln(myfirstjson.firstname); "// Outputs Mario document.writeln(myfirstjson.lastname); " // Outputs Rossi document.writeln(myfirstjson.age); " " " "// Outputs 23

Objects as Data var myfirstjson = { "firstname" : "Mario", " " " " " " " " " " "lastname" ": "Rossi", " " " " " " " " " " "age" " " " : 23 ; This data format is called JSON for JavaScript Object Notation. What makes it particularly powerful is that since the value can be any data type you can store other arrays and other objects nesting them as deeply as you need

Objects as Data var employees = { "accounting" : [ " // accounting is an array in employees. " " " " " " " " " " " " " " " " " " { "firstname" : "Mario", "// First element " " " " " " " " " " " " " " " " " " " "lastname" ": "Rossi", " " " " " " " " " " " " " " " " " " " "age" " " " : 23, " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " { "firstname" : "Luca", "// Second Element " " " " " " " " " " " " " " " " " " " "lastname" ": "Verdi", " " " " " " " " " " " " " " " " " " " "age" " " " : 32 " " " " " " " " " " " " " " " " " ], // End "accounting" array. " " " " " " " " " " " " " " " " " " " "sales" " " " : [ // Sales is another array in employees. " " " " " " " " " " " " " " " " " " { "firstname" : "Mario", // First Element " " " " " " " " " " " " " " " " " " " "lastname" ": "Biondi", " " " " " " " " " " " " " " " " " " " "age" " " " : 27, " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " { "firstname" : "Marco", " // Second Element " " " " " " " " " " " " " " " " " " " "lastname" ": "Arancio", " " " " " " " " " " " " " " " " " " " "age" " " " : 41 " " " " " " " " " " " " " " " " " ] // End "sales" Array. " " " " " " " " // End Employees employees is an object. That object has two properties or name/value pairs. accounting is an array which holds two JSON objects showing the names and age of 2 employees. sales is also an array which holds two JSON objects showing the name and ago of the two employees who work in sales. All of this data exists within the employees object.

Accessing Data In JSON The most common way to access JSON data is through dot notation This is simply the object name followed by a period and then followed by the name/property you would like to access. var myobject = { 'color' : 'blue' ; document.writeln(myobject.color); // outputs blue. If your object contains an object then just add another period and name var myobject = { 'color' : 'blue', " " " " " " " " "'animal' : {'dog' : 'friendly' " " " " " " " "; document.writeln(myobject.animal.dog); // outputs friendly

Accessing Data In JSON Using the employee example above if we wanted to access the first person who worked in sales document.writeln(employees.sales[0].firstname + ' ' + employees.sales[0].lastname); We can also access the second person who works in accounting document.writeln(employees.accounting[1].firstname + ' ' + employees.accounting[1].lastname);

Recap to recap... The employee example is an object which holds two arrays each of which holds two additional objects. The only limits to the structure are the amount of storage and memory available to it. Because JSON can store objects within objects within objects and arrays within arrays that can also store objects There is no virtual limit to what a JSON object can store. Given enough memory and storage requirement, a simple JSON data structure can store, and properly index, all the information ever generated by humanity.

Simulating An Associative Array You can also access JSON data as if it were an Associative Array. var myfirstjson = { "firstname" : "Mario", " " " " " " " " " " "lastname" ": "Rossi", " " " " " " " " " " "age" " " " : 23 ; document.writeln(myfirstjson["firstname"]); "// Outputs Mario document.writeln(myfirstjson["lastname"]); " // Outputs Rossi document.writeln(myfirstjson["age"]); " " " "// Outputs 23 Be aware that this is NOT an associative array, however it appears. If you attempt to loop through myfirstobject you will get in addition to the three properties above any methods or prototypes assigned to the object you're more than free to use this method of addressing JSON data just treat it for what it is (Object Properties) and not for what it is not (Associative Array)

Receiving JSON via AJAX There are three seperate ways to receive JSON data via AJAX. Assignment Callback Parse

JSON Via Assignment There's no standard naming convention for these methods however assignment method is a good descriptive name The file comming in from the server creates a javascript which will assign the JSON object to a variable when the responsetext from the server is passed through eval somevar will be loaded with the JSON object you can access it from there.

JSON Via Assignment // example of what is received from the server. var JSONFile = "somevar = { 'color' : 'blue' "; " // Execute the javascript code contained in JSONFile. eval(jsonfile); // It s amazing! document.writeln(somevar.color); // Outputs 'blue' When the responsetext from the server is passed through eval somevar will be loaded with the JSON object you can access it from there.

JSON Via Callback The second method calls a pre-defined function passing the JSON data to that function as the first argument A good name for this method is the callback method used extensively when dealing with third party JSON files (IE, JSON data from domains you do not control). function processdata(incommingjson) { " "document.writeln(incommingjson.color); // Outputs 'blue' // example of what is received from the server... var JSONFile = "processdata( { 'color' : 'blue' )"; eval(jsonfile);

JSON Via Parse As JSON is just a string of text it needs to be converted to an object before to make it useful. Although this can be done in JavaScript with the eval() function It is safer to use a JSON parser You can download the JavaScript JSON parser at http://www.json.org/json.js Including this file on a web page allows you to take advantage of the JSON object JSON.parse(strJSON) - converts a JSON string into a JavaScript object. JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.

JSON and PHP As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default. Decoding JSON string is very simple with PHP Only one line of code is needed to parse string into object. Similary only one function is needed to encode PHP object or array into JSON string <?php // decode JSON string to PHP object $decoded = json_decode($_get['json']);?> // create response object $json = array(); $json['errorsnum'] = 2; $json['error'] = array(); $json['error'][] = 'Wrong email!'; $json['error'][] = 'Wrong hobby!'; " // encode array $json to JSON string $encoded = json_encode($json);

AJAX database example The HTML page contains a link to an external JavaScript, an HTML form, and a div element: <html> <head> <script type="text/javascript" src="selectuser.js"></script> </head> <body> <form> Select a User: <select name="users" onchange="showuser(this.value)"> <option value="1">peter Griffin</option> <option value="2">lois Griffin</option> <option value="3">glenn Quagmire</option> <option value="4">joseph Swanson</option> </select> </form> <br /> <div id="txthint"><b>person info will be listed here.</b></div> </body> </html>

AJAX database example - The JavaScript var xmlhttp; function showuser(str) { xmlhttp=getxmlhttpobject(); if (xmlhttp==null) { ""alert ("Browser does not support HTTP Request"); ""return; var url="getuser.php"; url=url+"?q="+str; url=url+"&sid="+math.random(); xmlhttp.onreadystatechange=statechanged; xmlhttp.open("get",url,true); xmlhttp.send(null); function statechanged() { if (xmlhttp.readystate==4) { document.getelementbyid("txthint").innerhtml=xmlhttp.responsetext; function GetXmlHttpObject() { if (window.xmlhttprequest) { " // code for IE7+, Firefox, Chrome, Opera, Safari " return new XMLHttpRequest(); if (window.activexobject) { // code for IE6, IE5 " return new ActiveXObject("Microsoft.XMLHTTP"); return null;

AJAX database example - The PHP Page <?php $q=$_get["q"]; $con = mysql_connect('localhost', 'peter', 'abc123'); if (!$con) { ""die('could not connect: '. mysql_error()); mysql_select_db("ajax_demo", $con); $sql="select * FROM user WHERE id = '".$q."'"; $result = mysql_query($sql); echo "<table border='1'> <tr> <th>firstname</th> <th>lastname</th> <th>age</th> <th>hometown</th> <th>job</th> </tr>"; while($row = mysql_fetch_array($result)) { ""echo "<tr>"; ""echo "<td>". $row['firstname']. "</td>"; ""echo "<td>". $row['lastname']. "</td>"; ""echo "<td>". $row['age']. "</td>"; ""echo "<td>". $row['hometown']. "</td>"; ""echo "<td>". $row['job']. "</td>"; ""echo "</tr>"; echo "</table>"; mysql_close($con);?>