The simple application of AJAX technology in PHP development

Source: Internet
Author: User
Tags smarty template

Ajax is undoubtedly one of the hottest web development technologies to be fired in 2005, and of course, this credit is inseparable from Google. I am just an ordinary developer, the use of Ajax is not particularly much, I will simply put my use of the experience to say a bit. (This article assumes that the user already has basic web development capabilities such as JavaScript, HTML, CSS, etc.)

[Introduction to Ajax] Ajax is a Web application development method that uses client-side scripting to Exchange data with a Web server. Web pages can be dynamically updated without interrupting the interaction process for re-cropping.    With Ajax, users can create a direct, highly available, richer, and more dynamic Web user interface that is close to the local desktop app. asynchronous JavaScript and XML (AJAX) are not new technologies, but use several existing technologies-including cascading style sheets (CSS), JavaScript, XHTML, XML, and Extensible Style Language Transformations (XSLT). Develop Web applications that look and operate like desktop software.

[Ajax execution principle] an AJAX interaction begins with a JavaScript object called XMLHttpRequest. As the name implies, it allows a client script to execute an HTTP request and will parse the server response in an XML format. The first step in the AJAX process is to create a XMLHttpRequest instance.    Use the HTTP method (get or post) to process the request and set the destination URL to the XMLHttpRequest object. When you send an HTTP request, you do not want the browser to hang and wait for the server to respond, instead you want to continue to respond to the user's interface interaction through the page and process them after the server responds to the actual arrival. To accomplish this, you can register a callback function with XMLHttpRequest and dispatch the XMLHttpRequest request asynchronously. Control is immediately returned to the browser, and when the server response arrives, the callback function is called.

[Ajax Practical Application] 1. Initializing Ajax Ajax is actually invoking the XMLHttpRequest object, so first we have to call this object, and we build a function that initializes the Ajax:

/*** Initializes a XMLHTTP object */function Initajax () {var ajax=false;   try {ajax = new ActiveXObject ("Msxml2.xmlhttp");    } catch (e) {try {ajax = new ActiveXObject ("Microsoft.XMLHTTP");    } catch (E) {Ajax = false;   }} if (!ajax && typeof xmlhttprequest!= ' undefined ') {ajax = new XMLHttpRequest (); } return Ajax;}

You may say, this code because to call XMLHTTP components, is not only IE browser can make, not after I experiment, Firefox is also able to use. Before we perform any AJAX operation, we must first call our Initajax () function to instantiate an Ajax object.

2. Using get mode Now we're going to take the first step to execute a GET request and join the data we need to get/show.php?id=1, so what should we do? Suppose there is a link: <a href="/show.php?id=1">新闻1</a> when i click on the link, I do not want to be able to see the content of the link in any refresh, then what should we do?

Change the link to:  News 1 //and set a layer to receive news, and set it to not display: 
   
  
  Also constructs the corresponding JavaScript function: function getnews (NewsID) {//If the parameter NewsID is not passed in if (typeof (NewsID) = = ' undefined ') {return false;  }//need to make Ajax URL address var url = "/show.php?id=" + NewsID;   Gets the location of the news display layer var show = document.getElementById ("Show_news");  Instantiating an Ajax object var ajax = Initajax ();   Use Get method to request Ajax.open ("Get", url, True); Get execution Status Ajax.onreadystatechange = function () {//If the execution is in a normal state, then the returned content is assigned to the above specified layer if (ajax.readystate = = 4 && A    Jax.status = = () {show.innerhtml = Ajax.responsetext; }}//Send empty ajax.send (null); }

Then when the user clicks on the "News 1" link, the corresponding layer below will display the obtained content, and the page does not have any refresh.    Of course, we omitted show.php this file, we just assume that the show.php file exists, and can work properly from the database to the ID 1 of the news extracted. This way to adapt to any element of the page, including forms, and so on, in fact, in the application, the operation of the form is more, for the form, more use of the Post method, this will be described below.

3. The Post method is actually similar to the get mode, but slightly different when performing Ajax, let's briefly tell you about it. Suppose there is a user input data form, we do not refresh the user data to save the database, while giving the user a successful prompt.

Building a form that does not require attributes such as action or method is all done by Ajax. 
   
     name: 
    
    
Age:
Gender:
// Build a layer that accepts return information:

We see that the form above does not need to submit information such as Target, and the type of submit button is only button, then all operations are performed by the Saveuserinfo () function in the OnClick event. Let's describe this function:

function Saveuserinfo () {//Get accept return information layer var msg = document.getElementById ("msg");  Gets the form object and user information value var f = document.user_info;  var userName = F.user_name.value;  var userage = F.user_age.value;  var usersex = F.user_sex.value;  URL address of the receiving form var url = "/save_info.php";  The value of post is required, each variable is connected by & to var poststr = "User_name=" + userName + "&user_age=" + userage + "&user_sex=" + usersex;    Instantiation of ajax var ajax = Initajax ();   Open the connection via post Ajax.open ("Post", url, True);   Defines the transmitted file HTTP header information Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded");  Send post Data ajax.send (POSTSTR); Get execution Status Ajax.onreadystatechange = function () {//If the execution status is successful, then write the return information to the specified layer if (ajax.readystate = = 4 && ajax.    Status = = $) {msg.innerhtml = Ajax.responsetext; }   } }

The process of roughly using post is this way, of course, the actual development situation may be more complex, which requires developers to slowly pondering.

4. Asynchronous callbacks (pseudo-Ajax mode) in general, using GET, post Ajax we can solve the current problem, but the application of complexity, of course, in development we may encounter the inability to use Ajax, but we need to simulate the effect of Ajax,    Then we can use pseudo-Ajax to achieve our needs. The general principle of pseudo-Ajax is that we are still ordinary form submission, or something else, but we are to put the value of the target is a floating frame, so that the page does not refresh, but we need to see our execution results, of course, can use JavaScript to simulate the cue information, but,    This is not true, so we need our execution results to be asynchronous callbacks that tell us how the results are performed. Suppose we need to upload a picture, and need to know the status of the image upload, such as whether the upload is successful, the file format is correct, the file size is correct, and so on.    Then we need our target window to return the execution results to our window, so that we can successfully simulate the process of an Ajax call.    The following code is slightly more, and involves smarty template technology, if you do not understand, please read the relevant technical information. Uploading Files: upload.html

Upload form, specify the target property as floating frame iframe1
   
     Select the image to upload: 
    
    
// The layer displaying the cue information
//The floating frame used to make the target window

Processing the uploaded php file: upload.php

<?php/* defines constants *///defines the MIME format that allows uploads define ("Upload_image_mime", "image/pjpeg,image/jpg,image/jpeg,image/gif,image/x-png , image/png "); The picture allows size, byte define ("Upload_image_size", 102400),//Picture size in kilobytes to represent define ("upload_image_size_kb", 100); Image upload path define ("Upload_image_path", "./upload/"); Get the allowed image format $mime = explode (",", User_face_mime), $is _vaild = 0;//traverse all allowed formats foreach ($mime as $type) {if ($_files[' image '] ['  Type '] = = $type) {$is _vaild = 1; }}//if the format is correct and does not exceed the size of the upload if ($is _vaild && $_files[' image '] [' Size ']<=user_face_size && $_files[' image ' [' Size ']>0) {if (Move_uploaded_file ($_files[' image '] [' tmp_name '], User_image_path. $_files[' image ' [' name '])) {$u pload_msg = "Upload picture Success!"  ";  } else {$upload _msg = "Failed to upload picture file"; }}else{$upload _msg = "Upload picture failed, may be file exceeded". user_face_size_kb. " KB, or the picture file is empty, or the file is not in the correct format ";} Parse template file $smarty->assign ("Upload_msg", $upload _msg); $smarty->display ("Upload.tpl"); > template file: Upload.tpl{if $upload _msg! = ""}callbackmessage ("{$upload _msg}"); {/if}//callback's JavaScript function,Used to display information in the parent window function Callbackmessage (msg) {//To open parent.document.getElementById ("message") to the layer where the parent window displays the message. Style.display = "  Block ";  Write the message you get in this window parent.document.getElementById ("message"). InnerHTML = msg; And a message that is set to automatically close the parent window after 3 seconds is displayed SetTimeout ("Parent.document.getElementById (' message '). style.display = ' None '", 3000);}

The process of using asynchronous callbacks is a bit complicated, but the basic implementation of Ajax, as well as the function of information hints, if you accept the template information hint more, then you can also set the layer of the way to deal with, this improvise.

[Conclusion] This is a very good web development technology, although the occurrence of a long time, but now slowly fire up, but also want to bring a change in the web development community, let us toward the development of RIA (Rich client), of course, anything advantageous also has drawbacks, if too much use of javascript , then the client will be very bloated, not conducive to the user's browsing experience, how to achieve a fast pro-premise, but also to achieve a good user experience, which requires web developers to work together.

The simple application of AJAX technology in PHP development

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.