Php and Ajax instances

Source: Internet
Author: User
Tags smarty template

 

* ************** Ajax learning requires basic web development capabilities such as JavaScript, HTML, and CSS ******** ********

[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:

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 "> </a> News 1 </a>. When I click this link, I don't want to refresh it to see the link content. What should we do?

// Change the link:
<A href = "#" onclick = "getnews (1)"> News 1 </a>

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

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. getelementbyidx_x ("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:
<Div id = "msg"> </div>
 

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. getElementByIdx_x ("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
<Div id = "message" style = "display: none"> </div>

// 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 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 & amp; $ _ 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. getElementByIdx_x ("message"). style. display = "block ";
// Write the messages obtained in this window
Parent.doc ument. getElementByIdx_x ("message"). innerHTML = msg;
// Automatically close the display of messages in the parent window after being set to 3 seconds
SetTimeout ("parent.doc ument. getElementByIdx_x ('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.

 

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.