PHP using AJAX examples

Source: Internet
Author: User
Tags http request smarty template

[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 implementation Principles]

An AJAX interaction begins 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:
/**
* Initialization of 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 we first step to execute a GET request, join us need to obtain/show. Php?id=1 data, so what should we do?

Suppose there is a link: <a Href= "/show.php?id=1" > News 1 </a>, 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:
<a Href= "#" onclick= "Getnews (1)" > News 1 </a>

and set a layer to receive the news, and set to not show:
<div id= "Show_news" > </div>

Construct the corresponding JavaScript function at the same time:

function Getnews (NewsID)
{
If you don't pass the parameter NewSID in,
if (typeof (NewsID) = = ' undefined ')
{
return false;
}
The URL address that needs to be Ajax
var url = "/show.php?id=" + NewsID;

Get the position of the news display layer
var show = document.getElementById ("Show_news");

Instantiating an Ajax object
var ajax = Initajax ();

Request using Get method
Ajax.open ("Get", url, True);

Get Execution status
Ajax.onreadystatechange = function () {
If execution is normal, the returned content is assigned to the layer specified above
if (ajax.readystate = = 4 && ajax.status = 200) {
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= "Submitting form" onclick= "Saveuserinfo ()" "
</form>
Build a layer that accepts return information:
<div id= "MSG" > </div>

We see that there is no need to submit the target information in the form form above, and the type of the Submit button is just a button, then all operations are performed by the Saveuserinfo () function in the OnClick event. Let's describe this function:
function Saveuserinfo ()
{
Get the Accept return information layer
var msg = document.getElementById ("msg");

Get form objects and user information values
var f = document.user_info;
var userName = F.user_name.value;
var userage = F.user_age.value;
var usersex = F.user_sex.value;

Receive the URL address for the form
var url = "/save_info.php";

The value of the post is required to join each variable by &
var poststr = "User_name=" + userName + "&user_age=" + userage + "&user_sex=" + usersex;

Instantiating Ajax
var ajax = Initajax ();
 
To open a connection by 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 succeeds, the return information is written to the specified layer
if (ajax.readystate = = 4 && ajax.status = 200) {
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 as 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 that displays the cue message
<div id= "message" style= "Display:none" > </div>

A floating frame used to make a target window
<iframe name= "iframe1" width= "0" height= "0" scrolling= "no" > </iframe>

Processing uploaded php Files: upload.php
<?php

/* Define constant * *

To define a MIME format that allows uploads
Define ("Upload_image_mime", "image/pjpeg,image/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 kilobytes.
Define ("upload_image_size_kb", 100);
The path of the picture upload
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 no more than the size of the upload up
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 image failed, may be file over". user_face_size_kb. " KB, or the picture file is empty, or the file format is not correct;
}

Parsing template files
$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 in the parent window
function Callbackmessage (msg)
{
Open the layer where the parent window displays the message
Parent.document.getElementById ("message"). Style.display = "block";
Write the message from this window
Parent.document.getElementById ("message"). InnerHTML = msg;
and the message that automatically closes the parent window after 3 seconds is displayed
settimeout ("Parent.document.getElementById"). 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.

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.