IT Community - Software Programming, Web Development and Technical Support

AJAX introduction

This is a discussion on AJAX introduction within the PHP Programming forums, part of the Web Development category; Introduction: Although the concept isn't entirely new, XMLHttpRequest technology is implemented on more sites now than ever. Compatibility is ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 05-08-2007, 03:08 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default AJAX introduction

Introduction:

Although the concept isn't entirely new, XMLHttpRequest technology is implemented on more sites now than ever. Compatibility is no longer an issue (IE, Mozilla and Opera all support it), and the benefits to using it are amazing. There are too many PHP programmers avoiding any work with JavaScript beyond simple form validation, and for good reason. It's difficult to keep several languages proficiently under your belt. But using the XMLHttpRequest object is not as hard as everybody thinks, and you don't need to buy and memorize another reference manual.

Let's Get To It!

Asynchronous JavaScript and XML, or AJAX is a method of sending and receiving data (usually XML) from a server-side application through JavaScript. Since javascript offers the ability to change the contents of a web page on-the-fly, this technique allows web programmers to venture closer to programming truly interactive web applications similar to those built with Java and ActiveX.

If you're working for a small or medium sized company interested in implementing AJAX solutions, you might end up responsible for figuring out how.
XMLHttpRequest objects can be a simple way of getting data to and from a PHP application while keeping your client right at home on the same page. Our example today will allow a user to select a specific piece of software that your company makes. We will show a selection box with several categories. When a user selects a category, a request is sent to a PHP application which returns a list of applicable software. The information is used to generate a list of the results underneath the selection box. Since the information is not loaded with the initial page, your company saves bandwidth, and because the user doesn't have to bounce from page to page for results, he will find your company's page more inviting and faster to load.

Methods of sending data
1. POST
2. GET

Methods of Ajax objects:
1. Open
2. send
3. onreadystatechange
4. readyState
5. status
6. responseXML
7. responseText
8. setRequestHeader
9. overrideMimeType (In order to avoid a syntax error in Firefox, if the returned content is NOT valid XML, use the overrideMimeType method to set the content-type)

Step1: Component Initialization:
if (window.XMLHttpRequest)
{ // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{ // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
/* Make sure that the transaction has finished. The XMLHttpRequest object
has a property called readyState with several states:
0: Uninitialized
1: Loading
2: Loaded
3: Interactive
4: Finished */
Step3:
http_request.onreadystatechange = function()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
// alert( http_request.responseText );
if (return_xml)
{
eval(callback_function + '(http_request.responseXML,callback_param)' );
}
else {
eval(callback_function + '(http_request.responseText,callback_param)' );
}
} else {
alert('There was a problem with the request.(Code: ' + http_request.status + ')');
}
}
}

Step2:
http_request.open(method, url, true);
if( method == 'POST' ) http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send(sendtxt);


POST Method:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 03-14-2008, 11:19 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

hi,
More information on Ajax.

AJAX (Asynchronous JavaScript and XML), or Ajax, is a group of inter-related web development techniques used for creating interactive web applications. A primary characteristic is the increased responsiveness and interactivity of web pages achieved by exchanging small amounts of data with the server "behind the scenes" so that entire web pages do not have to be reloaded each time there is a need to fetch data from the server. This is intended to increase the web page's interactivity, speed, functionality, and usability.

AJAX is asynchronous; in that extra data is requested from the server and loaded in the background without interfering with the display and behavior of the existing page. JavaScript is the scripting language in which AJAX function calls are usually made.[1] Data is retrieved using the XMLHttpRequest object that is available to scripting languages run in modern browsers, or alternatively Remote Scripting in browsers that do not support XMLHttpRequest. There is, however, no requirement that the asynchronous content be formatted in XML.

AJAX is a cross-platform technique usable on many different operating systems, computer architectures, and web browsers as it is based on open standards such as JavaScript and the DOM. There are free and open source implementations of suitable frameworks and libraries.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 03-14-2008, 11:21 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Hi,
Here some status while Ajax processing as response from the following link

http://www.discussweb.com/html-css-j...atus-code.html
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 03-14-2008, 11:23 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Properties & Methods of Msxml2.XMLHTTP object

Properties
onreadystatechange - Specifys the event handler to be called when the readyState property changes.
readyState - represents the state of the request (ro)
responseBody - represents the results of the response as an array of unsigned bytes (ro)
responseStream - represents the results of the response as an IStream (ro)
responseText - represents the results of the response as a string (ro)
responseXML - represents the results of the response as parsed by the Microsoft XML Parser (ro)
status - The HTTP Status code returned by request (ro)
statusText - represents the HTTP response line status (ro)

Methods
abort
getAllResponseHeaders
getResponseHeader
open (method, url, boolAsync, bstrUser, bstrPassword) - (method Get, Post, Put, Profind)
send(varBody)
setRequestHeader(bstrHeader, bstrValue)
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 03-14-2008, 11:25 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Properties & Methods of MicrosoftXMLHTTP object

Properties
• async
boolean: specifies whether asynchronous download of the document is permitted.
• doctype
• documentElement
• implementation
• ondataavailable [ie]
• onreadystateChange [ie]
• ontransformnode [ie]
• parseError [ie]
• preserveWhiteSpace [ie]
• readyState
• resolveExternals [ie]
• setProperty ) [ie]
The following (2nd level) properties can be set:
o AllowDocumentFunction
o ForcedResync
o MaxXMLSize
o NewParser
o SelectionLanguage
o SelectionNamespace
o ServerHTTPRequest
for example:
xmlDoc.setProperty("SelectionLanguage", "XPath");
selection = xmlDoc.selectNodes("//Customer");
• url [ie]
• validateOnParse [ie]


Methods
• abort [ie]
• createAttribute
• createCDATASection (data )
• createComment (comment)
• createDocumentFragment (data )
• createElement (tagName)
• createEntityReference (name )
• createNode [ie] (type, name, nameSpaceURI)
• createProcessingInstruction (target, data)
• createTextNode (data)
• getElementsByTagName (tagName)
• load [ie] (url)
• loadXML [ie] (xml_string)
• nodeFromID [ie] (id_string)
• save [ie] (objTarget)
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 03-14-2008, 11:32 PM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: AJAX introduction

Hi Jey

I have one dout. How can we use the post method in the ajax can you please explain about that?

Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 03-14-2008, 11:50 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Hi,
Here i have given u the sample

ajax_test.php file contain

PHP Code:
<html>
<
body>
test on the Ajax Post method
<script language="javascript">
function 
ajaxcall(urlcallback_functioncallback_paramreturn_xml

    var 
xmlhttp false
    var 
method 'GET'sendtxt null;
    if( 
arguments.length == )
    {
        
method arguments[4];
        
sendtxt arguments[5];
    }

    if (
window.XMLHttpRequest) { // Mozilla, Safari,... 
         
xmlhttp = new XMLHttpRequest(); 
        
    } else if (
window.ActiveXObject) { // IE 
         
try { 
              
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
         } catch (
e) { 
              try { 
                    
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
              } catch (
e) {} 
         } 
    } 

    
xmlhttp.onreadystatechange = function() { 
        
//if( !ie && xmlhttp.aborted ) return;
         
if (xmlhttp.readyState == 4) { 
              if (
xmlhttp.status == 200  ) { 
                    if( 
xmlhttp.responseText == '' ) return;
                    if (
return_xml) { 
                         eval(
callback_function '(xmlhttp.responseXML,callback_param,xmlhttp.responseText)' ); 
                    } else { 
                         eval(
callback_function '(xmlhttp.responseText,callback_param)' ); 
                    } 
              } else if( 
xmlhttp.status != ) { 
                    
alert('There was a problem with the request.(Code: ' xmlhttp.status ':'+xmlhttp.responseText+')'); 
              } 
         } 
    } 
    
xmlhttp.open(methodurltrue); 
    if( 
method == 'POST' xmlhttp.setRequestHeader('Content-Type''application/x-www-form-urlencoded');
    
//if( !ie ) xmlhttp.aborted = false;
    
xmlhttp.send(sendtxt);
    return 
xmlhttp;
}
url "test1.php?rnd="+Math.random();
ajaxcall(url"fun"''0,"POST","txt1=testmessage"

function 
fun(txt,obj)
{
    
alert(txt);
}
</script>
</body>
</html> 
test1.php (Server response file)
PHP Code:
<?php
    
echo $_POST['txt1'];
?>
You can get alert message as u sent the param for the post method

Feel free to ask if u have any query
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 03-17-2008, 01:39 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: AJAX introduction

Hi,

This topic is very usefull to me. I think most of the web site created using Ajax.

how works ajax?

do you understand my question ? can anyone person tell me
__________________
Regards,
Senraj.A

Last edited by senraj : 03-18-2008 at 01:49 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 03-17-2008, 01:53 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Hi Senraj,

AJAX is a method of sending and receiving data (usually XML) from a server-side application through JavaScript. Since javascript offers the ability to change the contents of a web page on-the-fly, this technique allows web programmers to venture closer to programming truly interactive web applications similar to those built with Java and ActiveX.

I have attached the Diagram which gives you more details on its working flow

if you feel the image is not clear then click here http://www.discussweb.com/attachment...ction-ajax.jpg
Attached Images
File Type: jpg ajax.JPG (16.2 KB, 7 views)
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 03-17-2008, 01:58 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

hi,
Can anyone tell me what is the difference between synchronous and asynchronous calls?
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 03-17-2008, 10:26 PM
P.Sathiya P.Sathiya is offline
D-Web Trainee
 
Join Date: Mar 2007
Posts: 16
P.Sathiya is on a distinguished road
Default Re: AJAX introduction

hi jeyaseelan

synchronously

the JavaScript engine is blocked until the interaction with the server is complete.It works particularly well when the server is on the same machine, or nearby on the LAN. Unfortunately, it can perform very badly if the server is under heavy load, or if the browser is connected to the server over a slow link. Because the JavaScript engine is blocked until the request completes, the browser will be frozen

The user cannot cancel the request, cannot click away, cannot go to another tab. This is extremely bad behavior

asynchronously

When you set the asyncFlag flag to true, the JavaScript engine does not block. Instead the request returns immediately, with a potential action that will be triggered later
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 03-18-2008, 01:24 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: AJAX introduction

Hi,

Above your post is very nice.

Can anyone tell me which is best synchronous or asynchronous?
__________________
Regards,
Senraj.A

Last edited by senraj : 03-18-2008 at 01:49 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 03-18-2008, 03:36 AM
Kamalakannan Kamalakannan is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 299
Kamalakannan is on a distinguished road
Default Re: AJAX introduction

Hi Senraj,

Asynchronous is best way because no need to wait until get the response against our request.
__________________
Thanks & Regards,
R.Kamalakannan.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 03-18-2008, 04:22 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: AJAX introduction

Hi Kamal

Can you please explain about the Asynchronous concept with the javascript and how its working in AJAX

Thanks
Falcon

Last edited by Falcon : 03-18-2008 at 08:38 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 03-18-2008, 11:00 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Hi,
While opening the connection with the server using Ajax object, we use
Code:
httpobj.open(method, url, true);
In the above we are putting third parameter for async as true.
As Kamal told in the previous post, there is no need to wait until get the response against our request.

But i think it can't help if want to do the next process based on the response
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 03-18-2008, 11:21 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

The advantages of Ajax over classical web based applications are:

.Asynchronous —Ajax allows for the ability to make asynchronous calls to a web server. This allows the client browser to avoid waiting for all data to arrive before allowing the user to act once more.

.Minimal data transfer —By not performing a full postback and sending all form data to the server, the network utilization is minimized and quicker operations occur. In sites and locations with restricted pipes for data transfer, this can greatly improve network performance.

.Limited processing on the server —With the fact that only the necessary data is sent to the server, the server is not required to process all form elements. By sending only the necessary data, there is limited processing on the server. There is no need to process all form elements, process the viewstate, send images back to the client, and no need to send a full page back to the client.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 03-18-2008, 11:24 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

As a advantage from Ajax

XMLHttpRequest Can make requests to pages not set up for AJAX
Can set/get all HTTP headers Can make HTTP requests using any type (GET, POST, PROPFIND, and so on) Supports full control over POST requests, allowing for any type of data encoding
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #18 (permalink)  
Old 03-18-2008, 11:27 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

few more advantages from Ajax

IFrame can make POST and GET HTTP requests Supportes all modern browsers and Supports asynchronous file uploads

Cookies supports the largest number of browsers and Few implementation differences between browsers
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #19 (permalink)  
Old 03-18-2008, 11:43 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,162
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: AJAX introduction

Hi,
Sometimes i was trying to get data using Ajax by sending some parameter and if i want to get the different results with same parameter, then i get the result as i get earlier. After clear the cookie then it is coming correctly.
Then i have started to send additional parameter as "rnd="+Math.random()

the code is given below
Code:
var url = "test.php?val=test&rnd="+Math.random();
it is working now. I don't know the exact problem here
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #20 (permalink)  
Old 03-19-2008, 01:33 AM