Php ajax example _ PHP Tutorial

Source: Internet
Author: User
Php ajax example. [AJAX introduction] Ajax is a Web application development method that uses client scripts to exchange data with Web servers. Web pages can be dynamically updated without interrupting the interaction process and cutting them again. Use [AJAX introduction]

Ajax is a Web application development method that uses client scripts to exchange data with Web servers. Web pages can be dynamically updated without interrupting the interaction process and cutting them again. With Ajax, users can create direct, highly available, richer, and more dynamic Web user interfaces close to local desktop applications.

Asynchronous JavaScript and XML (AJAX) are not new technologies. They use several existing technologies, including Cascading Style Sheets (CSS), JavaScript, XHTML, XML, and extensible style language conversion (XSLT), develop Web applications that look and operate similar to 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 an HTTP request and parse a server response in XML format. The first step in Ajax processing is to create an 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 suspend and wait for the response from the server. Instead, you want to continue responding to user interface interactions through the page, and post-processing them after the server response actually arrives. To complete this, you can register a callback function with XMLHttpRequest and asynchronously dispatch the XMLHttpRequest request. The control right is immediately returned to the browser. when the server responds, the callback function will be called.

[AJAX application]

1. initialize Ajax

Ajax actually calls the XMLHttpRequest object. First, we must call this object. we construct an Ajax initialization function:
/**
* Initialize an 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 because the XMLHTTP component is called by the IE browser, this code can be used only by Firefox.
Before executing any Ajax operation, we must call our InitAjax () function to instantiate an Ajax object.

2. use the Get method

Now let's first execute a Get request. Do we need to Get/show. PHP? Id = 1 data, so what should we do?

Assume there is a link: <a href = "/show. php? Id = 1 "> News 1 </a>. when I click this link, I don't want to refresh it to see the link content. what should I do?
// Change the link:
<A href = "#" onClick = "getNews (1)"> News 1 </a>

// Set a layer for receiving news, and set it to not display:
<P id = "show_news"> </p>

At the same time, construct the corresponding JavaScript function:

Function getNews (newsID)
{
// If newsID is not passed in
If (typeof (newsID) = 'undefined ')
{
Return false;
}
// URL for Ajax
Var url = "/show. php? Id = "+ newsID;

// Obtain the position of the news display layer
Var show = document. getElementById ("show_news ");

// Instantiate an Ajax object
Var ajax = InitAjax ();

// Get Requests
Ajax. open ("GET", url, true );

// Obtain the execution status
Ajax. onreadystatechange = function (){
// If the execution is normal, the returned content is assigned to the layer specified above.
If (ajax. readyState = 4 & ajax. status = 200 ){
Show. innerHTML = ajax. responseText;
}
}
// Sending blank
Ajax. send (null );
}

When you click "News 1", The retrieved content is displayed at the corresponding layer below, and the page is not refreshed. Of course, the show. php file is omitted above. we just assume that the show. php file exists and can normally extract the news with id 1 from the database.

This method is applicable to any elements in the page, including Forms. In fact, there are many form operations in the application. for forms, the POST method is more used, the following is a description.

3. Use POST

In fact, the POST method is similar to the Get method, but it is slightly different when Ajax is executed. let's briefly describe it.

Suppose there is a user input data form, we save the user data to the database without refreshing, and give the user a success prompt.
// Construct a form. all attributes such as action and method are handled by ajax.
<Form name = "user_info">
Name: <input type = "text" name = "user_name"/> <br/>
Age: <input type = "text" name = "user_age"/> <br/>
Gender: <input type = "text" name = "user_sex"/> <br/>

<Input type = "button" value = "submit form" onClick = "saveUserInfo ()">
</Form>
// Construct a layer for receiving returned information:
<P id = "msg"> </p>

We can see that there is no need to submit the target information in the form above, and the type of the submit button is only a button, so all operations are executed by the saveUserInfo () function in the onClick event. Let's describe this function:
Function saveUserInfo ()
{
// Obtain the accept response information layer
Var msg = document. getElementById ("msg ");

// Obtain 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 of the received form
Var url = "/save_info.php ";

// The POST value is required to connect each variable through &
Var postStr = "user_name =" + userName + "& user_age =" + userAge + "& user_sex =" + userSex;

// Instantiate Ajax
Var ajax = InitAjax ();
 
// Open the connection through Post
Ajax. open ("POST", url, true );

// Define the HTTP header information of the transmitted file
Ajax. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");

// Send POST data
Ajax. send (postStr );

// Obtain the execution status
Ajax. onreadystatechange = function (){
// If the execution status is successful, the returned information is written to the specified layer.
If (ajax. readyState = 4 & ajax. status = 200 ){
Msg. innerHTML = ajax. responseText;
}
}
}

This is the process of using the POST method. of course, the actual development situation may be more complex, which requires developers to think about it.

4. asynchronous callback (pseudo Ajax)

Under normal circumstances, Ajax using Get and Post methods can solve the current problem, but the application complexity. of course, during development, we may encounter a problem where Ajax cannot be used, however, we need to simulate the Ajax effect, so we can use the pseudo Ajax method to achieve our needs.

The general principle of pseudo Ajax is that we are still submitting a common form or something, but we set the submitted value to a floating framework, so that the page will not be refreshed. However, we also need to see our execution results. of course we can use JavaScript to simulate the prompt information. However, this is not true, so we need our execution results for asynchronous callback, tell us how the execution result is.

Assume that we need to upload an image and know its status, for example, whether the image is uploaded successfully, whether the file format is correct, and whether the file size is correct. Then we need our target window to return the execution result to our window, so that we can smoothly simulate an Ajax call process.

The following code is a little more and involves the Smarty template technology. if you are not familiar with it, please read the relevant technical materials.

Upload File: upload.html
// Upload the form and specify the target attribute as the floating frame iframe1
<Form action = "/upload. php" method = "post" enctype = "multipart/form-data" name = "upload_img" target = "iframe1">
Select the image to upload: <input type = "file" name = "image"> <br/>
<Input type = "submit" value = "upload image">
</Form>
// Display the prompt information layer
<P id = "message" style = "display: none"> </p>

// Floating frame used for the target window
<Iframe name = "iframe1" width = "0" height = "0" scrolling = "no"> </iframe>

Process the uploaded php file: upload. php
<? Php

/* Define a constant */

// Define the MIME format that can be uploaded
Define ("UPLOAD_IMAGE_MIME", "image/pjpeg, image/jpg, image/jpeg, image/gif, image/x-png, image/png ");
// Size, in bytes allowed for the image
Define ("UPLOAD_IMAGE_SIZE", 102400 );
// The image size is measured in KB.
Define ("UPLOAD_IMAGE_SIZE_KB", 100 );
// Upload path
Define ("UPLOAD_IMAGE_PATH", "./upload /");

// Obtain the allowed Image format
$ Mime = explode (",", USER_FACE_MIME );
$ Is_vaild = 0;

// Traverse all permitted formats
Foreach ($ mime as $ type)
{
If ($ _ FILES ['image'] ['type'] = $ type)
{
$ Is_vaild = 1;
}
}

// Upload the file if the format is correct and the file size does not exceed the size
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 = "Image uploaded successfully! ";
}
Else
{
$ Upload_msg = "an error occurred while uploading the image file ";
}
}
Else
{
$ Upload_msg = "failed to upload the image. it may be because the file exceeds". USER_FACE_SIZE_KB. "KB, the image file is empty, or the file format is incorrect ";
}

// Parse the template file
$ Smarty-> assign ("upload_msg", $ upload_msg );
$ Smarty-> display ("upload. tpl ");

?>

Template File: upload. tpl

{If $ upload_msg! = ""}
CallbackMessage ("{$ upload_msg }");
{/If}

// Callback JavaScript function, used to display information in the parent window
Function callbackMessage (msg)
{
// Open the message layer in the parent window
Parent.doc ument. getElementById ("message"). style. display = "block ";
// Write the messages obtained in this window
Parent.doc ument. getElementById ("message"). innerHTML = msg;
// Automatically close the display of messages in the parent window after being set to 3 seconds
SetTimeout ("parent.doc ument. getElementById ('message'). style. display = 'none'", 3000 );
}

The process of using asynchronous callback is a bit complicated, but Ajax and information prompting are basically implemented. if there are many Template prompts, you can also set the layer to handle this problem.

Ajax is a Web application development method that uses client scripts to exchange data with Web servers. Web pages can be dynamically updated without interrupting the interaction process and cutting them again. Use...

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.