The simple application _php technique of AJAX Technology in PHP development

Source: Internet
Author: User
Tags smarty template

Ajax is undoubtedly one of the hottest web development technologies to fry in the 2005, and of course, this credit cannot be separated from Google. I am just an ordinary developer, the use of Ajax is not very much, I simply put the experience I used to say. (This article assumes that users already have basic web development capabilities such as JavaScript, HTML, CSS, etc.)

[Ajax Introduction] Ajax is a Web application development method that uses client script to exchange data with a Web server. Web pages can be updated dynamically without interrupting the interactive process. With Ajax, users can create a direct, highly available, richer, more dynamic Web user interface that is close to local desktop applications.

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 starts with a JavaScript object called XMLHttpRequest. As the name implies, it allows a client script to execute the HTTP request and will parse an XML-formatted server response. 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 target URL to the XMLHttpRequest object.

When you send an HTTP request, you do not want the browser to hang up and wait for the server to respond, instead, you want to continue to interact with the user's interface through the page and process them after the server response has actually arrived. To do this, you can register a callback function with XMLHttpRequest and distribute XMLHttpRequest requests asynchronously. Control is immediately returned to the browser, and the callback function is invoked when the server response arrives.

[Ajax Practical Application]

1. Initialize Ajax 

Ajax is actually calling the XMLHttpRequest object, so first we have to call this object, and we build a function that initializes 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 that this code because to call the XMLHTTP component, is not only IE browser can make, not by my experiment, Firefox can also be used. So before we do any AJAX operation, we must first invoke our Initajax () function to instantiate an Ajax object.

2. Using Get method   

Now the first step is to execute a GET request and join the data that we need to obtain/show.php?id=1, so what should we do?

Suppose there is a link: News 1 , when I click on the link, I don't want any refreshing to see the link content, so what do we do?

Change the link to:  News 1 //and set up a layer to receive the news, and set to not display: 
   
   
also constructs the corresponding JavaScript function: function getnews (NewsID) { //If the parameter NewsID is not passed in if (typeof (NewsID) = = ' und  Efined ') {return false; ///need Ajax URL address var url = "/show.php?id=" + NewsID; Get the position of the news display layer var show = document.getElementById ("Show_news"); Instantiate Ajax Object var ajax = Initajax (); Request Ajax.open using Get method ("Get", url, true); Gets the execution state ajax.onreadystatechange = function () { //If execution is normal, the returned content is assigned to the layer specified above (ajax.readystate   = = 4 && ajax.status = = show.innerhtml = ajax.responsetext; } //Send empty ajax.send (null); }

Then, when the user clicks the "News 1" link, the corresponding layer below will display the content, and the page is not refreshed.    Of course, we omitted the show.php file, and we just assumed that the show.php file existed and that it was able to extract the news ID 1 from the database correctly. This way to adapt to any element of the page, including forms, and so on, in fact, in the application of the form of the operation is more, for the form, more use is the Post method, this will be described below.

3. Use POST method  

In fact, the Post method is similar to get way, only slightly different in the implementation of Ajax, we simply tell.

If there is a user input form, we save the user data to the database without refreshing, and give the user a successful prompt.

Building a form that does not require attributes such as action, method, and so on, is all done by Ajax. <form name= "User_info" > name: <input type= "text" name= "user_name"/><BR/> Age: <input type= "text" name= "user_age"/><br/> Sex: <input type= "text" name= "User_sex"/><br/> <input type= "button" value= "Submit Form" onclick= "Saveuserinfo ()" > </form>//Build an acceptance Layers to return information: <div id= "MSG" > </div> we see that there is no need to submit the target in the form form above, and the type of the Submit button is just a button, then all operations are dependent on the Saveuserinfo in the onclick event () function to execute the.
 
  Let's describe this function: Functions Saveuserinfo () {//Get receive return information layer var msg = document.getElementById ("msg");
  Get 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;
 
  Receive form URL address var url = "/save_info.php"; 
 
  Need to post the value of each variable through & to join var poststr = "User_name=" + userName + "&user_age=" + userage + "&user_sex=" + usersex;
  
  Instantiate ajax var ajax = Initajax (); 
 
  Open the Connection Ajax.open ("Post", URL, True) by POST; Defines the transmitted file HTTP header information Ajax.setrequestheader ("Content-type", "application/x-wWw-form-urlencoded ");
 
  Send post Data ajax.send (POSTSTR); Get execution state ajax.onreadystatechange = function () {//If execution is successful, write the return information to the specified layer if (ajax.readystate = 4 && AJ 
   Ax.status = = Msg.innerhtml = Ajax.responsetext;
 }   } }

This is how the post approach is used, and of course, the actual development situation can be more complex, which requires the developer to slowly ponder.

4. Asynchronous callback (pseudo Ajax method)  

Under normal circumstances, using GET, post-style Ajax we are able to solve the current problem, but the application of complexity, of course, in development we may encounter can not use Ajax, but we need to simulate the effect of Ajax, then we can use the pseudo-Ajax way to achieve our needs.

Pseudo-Ajax general principle means that we are still ordinary form submission, or something else, but we're putting the value of the submission to a floating frame so that the page doesn't refresh, but then we need to see the results of our execution, and of course we can use JavaScript to simulate the hints, but This is not true, so we need our execution results to asynchronously callback and tell us what the result is.

Let's say we need to upload a picture, and we 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 windows so that we can simulate the process of an Ajax call smoothly. The following code is slightly more, and involves smarty template technology, and if not, read the relevant technical information.

Upload file: upload.html

Upload form, specify target property for floating frame iframe1 <form action= "/upload.php" method= "post" enctype= "Multipart/form-data" name= "Upload_" IMG "target=" "iframe1" > Select the picture to upload: <input type= "file" name= "image" ><br/> "<input type=" submit "value=" Upload picture "> </form>// The layer <div id= "message" style= "Display:none" that displays the hint is </div>//the floating frame used to make the target window <iframe name= "iframe1" width= "0" height= "0" Scrol Ling= "No" > </iframe> process uploaded php file: upload.php <?php/* Define constant////definition allow upload of MIME format define ("Upload_image_mime", "Image/pjpeg,im 
Age/jpg,image/jpeg,image/gif,image/x-png,image/png ");
Picture allowed size, byte define ("Upload_image_size", 102400); 
The picture size is expressed in KB for define ("upload_image_size_kb", 100); 
 
Picture upload path define ("Upload_image_path", "./upload/");
Gets the allowed image format $mime = explode (",", user_face_mime);
 
$is _vaild = 0;
  Traverses all allowed format foreach ($mime as $type) {if ($_files[' image '] [' type '] = = $type) {$is _vaild = 1; }//If the format is correct and does not exceed the size to 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 ']) {$upload _msg = "Upload picture Success!"
  ";
  else {$upload _msg = "Upload image file failed"; } else {$upload _msg = "Upload picture failed, possibly file is over". user_face_size_kb. "
KB, or the picture file is empty, or the file format is not correct;
//Parse template file $smarty->assign ("Upload_msg", $upload _msg);
 
$smarty->display ("Upload.tpl");
 ? >

Template file: Upload.tpl

{if $upload _msg!= ""}
Callbackmessage ("{$upload _msg}"); 
{/if}
 
The JavaScript function of the callback used to display information
function callbackmessage (msg)
{
//To open
the layer of the parent window to display the message in the parent window  Parent.document.getElementById ("message"). Style.display = "block";
Write the message from this window
parent.document.getElementById ("messages"). InnerHTML = msg;
and the message that automatically closes the parent window after 3 seconds displays
settimeout ("parent.document.getElementById" (' message '). style.display = ' None ', 3000);
}

The way to use asynchronous callback is a bit complicated, but the basic implementation of Ajax, as well as information prompts the function, if the template to receive more information, then you can set the layer of the way to deal with it.

[Concluding remarks] this is a very good web development technology, although the occurrence of a relatively long time, but only now slowly, but also hope to bring a change in the web development community, let us towards the RIA (rich client) development, of course, anything beneficial 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 do a good user experience, which requires web developers to work together.

The above is the entire content of this article, I hope to master Ajax technology in the development of a simple PHP application Help.

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.