PHP using Ajax sample _php Tutorial

Source: Internet
Author: User
Tags smarty template
[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 called the XMLHttpRequest object, so first we have to call this object, we build a function to initialize Ajax:
/**
* Initialize 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. Use the Get method

Now we take the first step to execute a GET request and join we need to get/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 to be able to see the content of the link without any refresh, so what do we do?
Change the link to:
<a Href= "#" onclick= "Getnews (1)" > News 1 </a>

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

Also constructs the corresponding JavaScript function:

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

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

Instantiating an Ajax object
var ajax = Initajax ();

Request by using Get method
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 layer specified above
if (ajax.readystate = = 4 && ajax.status = = 200) {
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. Use the Post method

In fact, the Post method is similar to the Get method, but in the implementation of Ajax slightly different, we briefly tell.

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.
<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>
Build a layer that accepts return information:
<div id= "MSG" > </div>

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");

Get Form object 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 of the form
var url = "/save_info.php";

The value of post is required, and each variable is joined by &
var poststr = "User_name=" + userName + "&user_age=" + userage + "&user_sex=" + usersex;

Instantiation of Ajax
var ajax = Initajax ();
 
Open 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 = = 200) {
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 way 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 target property as floating frame iframe1
<form action= "/upload.php" method= "post" enctype= "Multipart/form-data" name= "upload_img" target= "iframe1" >
Select the picture you want to upload: <input type= "file" name= "image" ><BR/>
<input type= "Submit" value= "Upload image" >
</form>
Layers that display informational messages
<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 the uploaded php file: upload.php
<?php

/* Define Constants */

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 allows size, bytes
Define ("Upload_image_size", 102400);
The picture size is expressed in kilobytes.
Define ("upload_image_size_kb", 100);
Path to image upload
Define ("Upload_image_path", "./upload/");

Get the allowed image formats
$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 not larger than the size, upload it.
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 Successfully! ";
}
Else
{
$upload _msg = "Failed to upload image 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 format is incorrect ";
}

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 to display the information in the parent window
function Callbackmessage (msg)
{
Opens the layer where the parent window displays the message
Parent.document.getElementById ("message"). Style.display = "block";
Write the message you get from this window.
Parent.document.getElementById ("message"). InnerHTML = msg;
and sets the message display to automatically close the parent window after 3 seconds
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.

http://www.bkjia.com/PHPjc/631861.html www.bkjia.com true http://www.bkjia.com/PHPjc/631861.html techarticle [Ajax Introduction] Ajax is a Web application development method that uses client script to exchange data with a Web server. Web pages can be dynamically updated without interrupting the interaction process for re-cropping. Use ...

  • Related Article

    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.