PHP and Ajax examples

Source: Internet
Author: User
In this article we will share with you the Ajax Basics, PHP and Ajax, JSON format, jquery Ajax, I hope this article can help everyone.

1.AJAX Foundation

(1) AJAX (Asynchronous JavaScript and XML): Asynchronous JavaScript and XML abbreviations.

(2) Ajax is not a programming language, but a technique for updating parts of a Web page without having to load the entire page.

(3) The disadvantage of traditional Web page: Need to update the content or submit a form, need to reload the entire page, using AJAX advantages: By the background and the server for a small amount of data exchange, the Web page can be implemented asynchronously local update. There is a very good user experience for filling out complex forms.

(4) Ajax synchronous and asynchronous: Synchronous is to load the entire page, asynchronous to load some pages. Specifically, the client-to-server connection. Before the advent of Ajax technology, it was a synchronous exchange of data, which would be cumbersome if the more complex forms were filled in. With the XMLHttpRequest object, the synchronized world becomes the asynchronous world. The object can be exchanged with the server through XMLHttpRequest.

(5) XMLHttpRequest Object creation: var requerst=new XMLHttpRequest(); directly instantiate an Object! Note: IE5 and IE6 do not support this definition, as shown in the following code if you want to implement browser page compatibility:

var request;if (window. XMLHttpRequest) {    request  = new XMLHttpRequest ();  Ie7+,firefox,chrome,opera,safari ...} else{    request = new Activeobject ("Microsoft.XMLHTTP");//IE6,IE5}

(6) HTTP request: HTTP is a stateless protocol: plainly, it is impossible to establish a persistent connection without a memory protocol. Further: through the page request and the response process, implements the Web page debugging.

(6.1) A complete HTTP request process, usually with the following 7 steps:

    • Establish a TCP connection

    • Web browser sends request command to Web server

    • Web browser sends request header information

    • Web server Answer

    • Web server sends answer header information

    • Web server sends data to browser

    • Web server shuts down TCP connection

(6.2) HTTP requests are generally made up of four parts:

    • The method or action of an HTTP request, such as a GET or POST request

    • The URL being requested, always know what the requested address is.

    • The request header, which contains some client environment information, authentication information, etc.

    • The request body, that is, the request body, the request body can contain customer submitted query payment wear information, form information and so on

(6.3) Get vs. Post [Collect name values from method= ' post/get ' form]

It's all about collecting the values that come from the form. Pass the value of the past, a form of a URL (unsafe), a value of the display (security); Get is generally used for information acquisition, using URL pass parameters , limited to 2000 characters, visible to all, unsafe. Post is typically used to send data from a form , with parameters in the HTTP request body, without limiting the number of messages sent.

(6.4) The HTTP response is typically made up of three parts:

    • A status code consisting of a number and text to indicate whether the request was successful or failed;

    • Response header, including server type, date time, content type and length, etc.;

    • The response body, which is the response body.

(6.5) The HTTP status code consists of three digits, with the first number defining the type of the status code:

    • 1XX: Information class, indicating receipt of Web browser requests, is being further processed;

    • 2XX: Successful, indicates that the user request is received, understood and processed correctly, for example:

    • 3XX: Redirect to indicate that the request was unsuccessful and the customer must take further action

    • 4XX: Client error, indicating that the client submitted a request with an error, such as 404 Not FOUND, means that the document referenced in the request does not exist.

    • 5XX: Server error, indicating that the server could not complete processing of the request.

(7) XMLHttpRequest Send Request: (Method of Object)

    • Open (method request, URL request address, async request Synchronous or asynchronous (async is True, synchronization is False, the default is true));/// invoke asynchronous request

    • Send (String);(when using the Get method, parameters can be left empty or null, since the information is included in the Address bar URL;// send the request to the server

Give me a chestnut:

Request.open ("POST", "create.php", true); Request.setrequestheader ("Content-type", "application/ X-www-form-urlencoded ");//Set HTTP header information to tell the Web server to send a form; Note: Setrequest requests must be placed between open and send, otherwise an exception will be thrown Request.send (" name = King Sledgehammer &sex= male ");

(8) XMLHttpRequest Get Response: (Methods and properties of the object)

    • responsetext: Simply put: The receiving server responds with the loopback data. Gets the corresponding data in the form of a string.

    • Responsxml: Gets the corresponding data in XML form. It is now generally converted to data in JSON form.

    • Status and StatusText: Returns the HTTP status code in both numeric and textual form.

    • Getallresponseheader (): Gets all the response headers.

    • getResponseHeader (): The value of a field in the query response.

ReadyState property: Gets notified when the response returns successfully.

    • 0: The request was not initialized and open has not yet been called.

    • 1: The server connection has been established and open has been called.

    • 2: The request has been received, that is to receive the header information.

    • 3: The request is processed, that is, the response body is received.

    • 4: The request is complete and the response is ready, that is, the response is complete.

a chestnut : covers most of the Ajax content (typical XHR building Ajax processes)

var request = new XMLHttpRequest ();//Create XHR Object Request.open ("GET", "get.php", true);//Invoke asynchronous Requests request.send ();//Send asynchronous request// Listen to the event to determine if the server is responding correctly request.onreadystatechange = function () {  if (request.readystate===4 && Request.status = = =) {    request.reponsetext;//receive server response loopback data   }}

2.PHP and Ajax

actual combat: [Server-side vs. client] Implement background interface for querying employees and new employees

(1) Client part code:

New Employee client code document.getElementById ("Save"). Onclick=function () {var request=new xmlhttprequest ();//Create XHR Object Request.open ("POST", "action.php");//The URL//document.getelementbyid ("Staffname") that calls the//data stitching of the asynchronous request. Value gets the values written by the user in the form V AR data = "username=" + document.getElementById ("Staffname"). Value + "&num=" + Document.getelementby    Id ("Staffnumber"). Value + "&workname=" + document.getElementById ("Staffjob"). Value; Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");//Set HTTP header information Request.send (data);//            Sends an asynchronous request//listens to the event to determine if the server responds correctly request.onreadystatechange=function () {if (request.readystate===4) { if (request.status===200) {//innerhtml can not only read element content, but also write content to an element//ajax engine object via ResponseText attribute or resp The Onsexml property receives the data that the server sends back, and then processes it in a static page so that the page achieves the effect of a local refresh document.getElementById ("Createresult"). INNERHTML=REQUEST.R            Esponsetext; }else{alter ("OccurrenceError: "+request.status); }        }    }}

(2) server-side part of the code:

Query Employee server-side code <?php header (' Content-type:text/html;charset=utf8 '), $con =mysqli_connect ("127.0.0.1", "", ""); mysqli_select_db ($con, "function"), $sql = "select * from ' Ajax '", $query =mysqli_query ($con, $sql);//total number of bars in database data $number$ Number=mysqli_num_rows ($query); for ($i =0; $i < $number; $i + +) {    //convert each piece of data to an associative array to print    $arr =mysqli_fetch_row ( $query);    Print_r ($arr);    Echo $arr [2];d ie;    if ($_get[' num ']== $arr [2]) {        echo "found employee: number $arr[2], name: $arr [1], Position: $arr [3]";        break;    }} ?>

3.JSON format

(1) Json:javascript object representation.

(2) JSON is the syntax for storing and exchanging textual information, similar to XML. It is organized by the way of key-value pairs , which is easy for people to read and machine parse.

(3) JSON is language-independent and can parse JSON in any language, as long as the JSON rules are in line.

(4) JSON is smaller in length than XML, JSON reads and writes faster, JSON can be directly parsed using JS built-in method and converted to JS object, which is very convenient.

(5) JSON syntax rules: The writing format of JSON data is: name/value pairs .

Names in name/value pairs are written in front (in double quotes), value pairs are written behind (also in double quotes), separated by colons, for example "name":"王大锤" . Note : JSON differs from JavaScript Object notation in that the key value of the JavaScript Object notation does not need to be quoted, but the key value of the JSON is quoted.

Note : JSON can be integer, float, string (in double quotation marks), Boolean (True or False), array (in square brackets), object (in curly braces), NULL, and so on data types.

Give me a chestnut:

{//Defines a JSON object  "staff": [//defines an array    {"name": "King Sledgehammer", "age": 21},//defines a name object    {"name": "Call Beast", "Age": 35}  ]}

(6) JSON parsing: eval () and Json.parse () two ways to parse into JSON form

Comparison of two methods: it is recommended to use the Json.parse () method to parse into JSON form

eval (); Unsafe if there is a function in JSON or JS program code (alert or a window.location.href () Jump link virus website, etc.), will take precedence of code, dangerous operation. Json.parse (); The JSON file has a checksum function, if there is a program in the JSON file script, will parse the error.

Give me a chestnut:

var jsondata= ' {' Staff    ': [{            ' name ': ' King Sledgehammer ', ' age ': ' {'} ', '            name ': ' Beast ',            ' age '        :        {            "name": "Wang Nima",            "age": +        }    ]} '; var jsonobj=json.parse (jsondata);//json.parse parsing Jsonvar Jsonobj=eval (' (' + jsondata + ') ');//eval parsing Jsonalert (jsonobj.staff[0].name);

Note : The above writing is wrong, just to see clearly. Comma is not a delimiter, the comma is the text content, all should be compact, not to see for themselves, the artificial space to separate. (The one-hour error is found here ...)

(7) JSON validation tool: Jsonlint

(8) Raise a chestnut:

Using JSON, you first need server-side conventions, which can reduce more judgment, display {    //front-end rule validation, back-end data validation "Success" in a more elegant form    : true,//is executed correctly (rules validation like forms)    "MSG": "XXX"//The requested response value is successful (information returned by HTTP response)}
server-side section code:
echo "parameter error, employee information not complete"; Echo ' {"Success": false, "MSG": "Parameter error, employee information not complete"} '; if ($query) {    //echo "employee:". $_post[" Username "]. "Information saved successfully!" ";    Echo ' {' success ': true, ' msg ': ' Employee saved successfully '} '; else{    //echo "Employees:". $_post["username"]. "Information save failed!" ";    Echo ' {"Success": false, "MSG": "Employee Save Failed"} ';}
Client JSON code: Other unchanged, the server-side response passed ResponseText (text form) into (JSON form), the JSON string into a JSON object data, and then be able to process the data as an object
    Request.onreadystatechange=function () {        if (request.readystate===4) {            if (request.status===200) {                // Converts the server-side response responsetext (text form) to (JSON form)                //Converts the JSON string to a JSON object data                var data=json.parse ( Request.responsetext);                if (data.success) {                    document.getElementById ("Createresult"). innerhtml=data.msg;                } else{                    document.getElementById ("Createresult"). Innerhtml= "error occurred" +DATA.MSG;}}}    

Ajax in 4.jQuery

(1) using jquery to implement AJAX requests: role: Avoid compatibility problems, code concise, fast and convenient operation.

(2) Syntax: Jquery.ajax ([Settings])

    • Type: Type, "POST" or "get", default to "get".

    • URL: The address where the request was sent.

    • Data: Is an object that is sent to the server, along with the request.

    • DataType: The data type that is expected to be returned by the server. If not specified, jquery will automatically be based on the HTTP packet MIME information to intelligently judge, generally we use the JSON format, can be set to "JSON."

    • Success: is a method that destroys a function after a successful request. The data after the incoming return, and the string containing the success code.

    • Error: is a method that calls this function when a request fails. Incoming XMLHttpRequest object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.