473,696 Members | 1,857 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XMLHttpRequest and AJAX for PHP programmers


XMLHttpRequest and AJAX for PHP programmers
James Kassemi

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.
As PHP developers, it might seem tempting to avoid the use of
Javascript and leave it to the dsigner. After all, we aren't usually
programming the UI, but the processing components required by the UI.
The distinction between the two is disappearing. Here's a simple
diagram that demonstrates just how AJAX works:

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.
Javascript for PHP Programmers
Since we'll be working with Javascript, it's good to get a basic
tutorial given a background in PHP.
Variables in javascript are declared in much the same was as in PHP.
To declare a variable in javascript, use the following:

[javascript code]
var varname = varvalue; //Declaring your variable is not mandatory,
but good practice.

Variable types are handled loosely, as they are in PHP.
Control Structures:
PHP and javascript have a very similar way of using these as well...
You can use if/else statements, switch statements, for and while loops
and nested loops all with PHP syntax. If/elseif/else statements are a
little different, but not much:

[javascript code]
var variable1 = 1; //Declare a variable.
if(variable1 == 1){
// Increment variable value by 1
/* The following brings up a message box, a handy way of
variable values as you
go. Be careful not to use these in
loops that are too long. */
alert(variable1 );
}else if(variable1 == 2){ //Elseif's in javascript require a space

between the else and if.
for(i=0;i<20;i+ +){ //For loop.
switch(variable 1){ //Switch conditional
case 22:
alert("variable 1 has value of 22!");
alert("didn't have value of 22!");

alert('The final else statement');


To declare a function in javascript, use the following:

[javascript code]
function functioname(arg ument1, argument2, argument3){
/* Arguments not provided will be null */
if(argument3 == null){
return argument1 + argument2
return argument1 + argument2 + argument3


/* And call it with */
alert(functionn ame(1, 2)); //returns 3
/* or */
alert(functionn ame(1, 2, 3)); //returns 6

Other than the difference with default values for optional arguments,
you should assign a default when a passed argument has a null value.
Using Javascript in a Document:
Javascript can be included in your document in two ways, similar to
CSS inclusion:

[HTML code]
<!--Placing your javascript in the head tag of your html document is
the standard-->
<script language="javas cript" type="text/javascript" src="./
javascript_file .js"></script>
<script language="javas cript" type="text/javascript">

/*Javscript code goes in here*/
alert("Hello World!");

The first way is to link to the file directly, and the second is to
include it on the page itself. If your code is getting long and is
used on multiple pages, it is preferable to use the first method, as
the browser will cache the file for future use. And that's all you
need to know about Javascript to continue.
Developing the Initial Page
Below we're going to be creating the page the user loads to view your
companies products.

[HTML code]
<title>CompanyX YZ Software</title>
<script language="javas cript" type="text/javascript"
src="./internal_reques t.js">

<div id="product_cat egories">
<!--Category selection box...-->
<form name="form_cate gory_select">

<option>Audio </option>
<option>Games </option>
<option>Interne t</option>

<div id="product_cag e">
<!--This is where we'll be displaying the
products once they're
^ Please select a category from above.


The above HTML first links to a javascript file, internal_reques t.js,
and displays a page with two <divtags, the second of which is where
we'll be displaying our data. Go ahead and copy the above code into a
file called products.html.
Creating the XMLHttpRequest Object
The XMLHttpRequest object works differently in Internet Explorer and
Mozilla-like browsers. To create an XMLHttpRequest object in IE, the
following can be used:

[javascript code]
var request_o = new ActiveXObject(" Microsoft.XMLHT TP");

And the following works for supporting browsers other than IE:

[javascript code]
var request_o = new XMLHttpRequest( );

Determining what browser you are working with and creating the
appropriate object is simple:

[javascript code]
/* The following function creates an XMLHttpRequest object... */

function createRequestOb ject(){
var request_o; //declare the variable to hold the object.
var browser = navigator.appNa me; //find the browser name
if(browser == "Microsoft Internet Explorer"){
/* Create the object using MSIE's method */
request_o = new ActiveXObject(" Microsoft.XMLHT TP");
/* Create the object using other browser's method */
request_o = new XMLHttpRequest( );
return request_o; //return the object


/* You can get more specific with version information by using
parseInt(naviga tor.appVersion)
Which will extract an integer value containing the version
of the browser being used.

Copy the above code into a file called internal_reques t.js, located in
the same directory as the products.html file.

We now have a function that will create an XMLHttpRequest object in
internal_reques t.js, and we have an HTML file that calls upon the code
in internal_reques t.js. Remember how we left the product selection
<divin products.html blank? Let's write the code that utilizes our
createRequestOb ject function to get the list of products.

[javascript code]

/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestOb ject();

/* Function called to get the product categories list */
function getProducts(){
/* Create the request. The first argument to the open function
is the
method (POST/GET),
and the second argument is the url...
document contains references to all items on the page
We can reference
document.form_c ategory_select. select_category _select and we will
be referencing the dropdown list. The selectedIndex
property will
give us the
index of the selected item.
http.open('get' , 'internal_reque st.php?
action=get_prod ucts&id='
document.form_c ategory_select. select_category _select.selecte dIndex);
/* Define a function to call once a response has been
received. This
will be our
handleProductCa tegories function that we define below.
http.onreadysta techange = handleProducts;
/* Send the data. We use something other than null when we are
sending using the POST
method. */
http.send(null) ;


/* Function called to handle the list that was returned from the
internal_reques t.php file.. */
function handleProducts( ){
/* Make sure that the transaction has finished. The
has a property called readyState with several states:
0: Uninitialized
1: Loading
2: Loaded
3: Interactive
4: Finished */
if(http.readySt ate == 4){ //Finished loading the response
/* We have got the response from the server-side
let's see just what it was. using the
responseText property of
the XMLHttpRequest object. */
var response = http.responseTe xt;
/* And now we want to change the product_categor ies
we do this using an ability to get/change the
content of a page
that we can find: innerHTML. */
document.getEle mentById('produ ct_cage').inner HTML =


The above code should be appended to what you already have in the
internal_reques t.js file.
We'll followup with the rest of this informative article next week, so
be sure to visit us again for the conclusion! btw, don't miss the
important Quick Tips listed below!
Quick Tip 1: (Using the POST method instead of GET):
The following will send the request to the PHP file using the POST

http.open('post ', 'back_end.php') ;
http.setRequest Header('Content-Type', 'application/x-www-form-
http.send('arg1 =val1&arg2=val2 &arg3=val3') ;

Quick Tip 2: (Parsing XML results):
If you're receiving XML instead plain-text results from your
processing PHP script, you can use the javascript DOM to parse them.
Suppose you receive the following:

<product_list >
<product id="1">
<name>EeasySM S</name>
<product id="2">
<name>BabyMon </name>

To receive a DOM compatible response from our XMLHttpRequest object,
instead of using the responseText property, substitute the responseXML
property. In this case we'll refer to it by assigning it the variable
The product_list element contains two elements of interest: product
elements. In order to get to these, we can use the following:

/* Reference the product_list element to the variable product_list */
product_list = XMLReponse.getE lementByTagName ('product_id');

/* By substituting product_list for XMLResponse, we will be searching
only the product_list element, not the entire response
We also use getElementsByTa gName, not getElementByTag Name,
since we are interested in all of the results, not just one.

product_id = XMLResponse.get ElementsByTagNa me('product');

/* getElementsByTa gName produces an array, which we can access like
product_id[n], the same way we access an array item in PHP.
Let's get the id attribute from the product elements like
this: */

for(i=0; i<product_id.le ngth; i++){ //length is the same as
id = product_id[i].getAttribute(' id') //Grabs the id
/* To get the text from within a text node, we use
for the corresponding element. */
name =
product_id[i].getElementByTa gName('name').f irstChild.data;
version =
product_id[i].getElementByTa gName('version' ).firstChild.da ta;


This may seem like a bit to work with at first, but with a little
work, you can get what you want to work. If you want to avoid this,
you could use the responseText method, parsing the XML in PHP before
sending it to the XMLHttpRequest object.
Quick Tip 3: (Relevant Links):

* Microsoft XMLHttpRequest Documentation
* XMLHttpRequest @ Apple Developer Connection
* The DOM Model in Mozilla

About the Author:
James Kassemi lives in Albuquerque, New Mexico. He works mainly with
PHP, programming for a variety of clients in the southwest.

Mar 27 '07 #1
1 4028
geevaa wrote:

Determining what browser you are working with and creating the
appropriate object is simple:

[javascript code]
/* The following function creates an XMLHttpRequest object... */

function createRequestOb ject(){
var request_o; //declare the variable to hold the object.
var browser = navigator.appNa me; //find the browser name
if(browser == "Microsoft Internet Explorer"){
/* Create the object using MSIE's method */
request_o = new ActiveXObject(" Microsoft.XMLHT TP");
/* Create the object using other browser's method */
request_o = new XMLHttpRequest( );
return request_o; //return the object


/* You can get more specific with version information by using
parseInt(naviga tor.appVersion)
Which will extract an integer value containing the version
of the browser being used.

This is getting totally off topic (PHP), but I must make a little
The above method of getting the browserspecific XMLHTTP-thingy is well...
Browsersniffing , as the above code does, is frowned upon by the better part
of the JavaScript-community.
It is much better to simply test for the existance of the needed object
instead of branching on appName and appVersion.

Similar to the test if the browser support images:
if (document.image s){
alert("You have imagesupport.") ;
} else {
alert("You have NO imagesupport. Are you still running LYNX?");
alert("By the way: Does LYNX support Javascript at all?");

You should do the same with the XMLhttp-thing.

Avoiding browsersniffing saves you a headache too. Like the many what-if
situations like: IE, but without scripted ActiveX, or older versions, etc.
Simply test if the object is supported by the browser keeps things clean and
It is also your best bet that your script keeps working if new
browserversions (or browsers) are released.

www.w3schools.com/ajax has a good example of how to get that object, simply
by testing the existance of the various flavors around, and returning them
on succes.

Just my 2 cent..

Erwin Moller
Mar 27 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Greg | last post by:
Hi, I've designed a bookmark in Ajax / PHP that I will put soon on sourceforge.net. But I've got an very tricky bug. I try it on some computers with Internet Explorer/Windows, Firefox 1.07/Linux, Firefox 1.5/Linux, Firefox 1.5/Windows and Firefox 1.5/Mac, Safari/Mac. It works perfectly on a lot of configurations but, on some PC with Firefox 1.5/Windows (not all), the Javascript code with XmlHttpRequest
by: mathewda | last post by:
Hey, I'm having a problem that I consider kinda weird that is alluding me at the moment. I've wrote some code that will set up an XMLHttpRequest, it then makes a call to open and send and sets the onreadystatechange to another function of mine. onreadystatechange checks the ready state and if the ready state is 4 and the status is 200 it assigns to the innerHTML of a div. I also have some code that uses the attachEvent method so that all...
by: pamelafluente | last post by:
The precious input given by Laurent, Martin, Benjamin about XMLHttpRequest in Javascript, has made me think that perhaps I could improve what I am currently doing by using Ajax. Let's make it simple and schematic, to see if there is a simple Ajax answer to this. A. I have an HTML page which has some pure html/css code representing a GRID of cell. The page may also contain other objects (images, etc). B. On the server I have a windows...
by: libsfan01 | last post by:
In IE6 i get an error: "XMLHttpRequest is undefined", whereas in other browsers (e.g. ie7) it works fine: var get; function getdata(region,page) { get = new XMLHttpRequest(); get.onreadystatechange = processdata;
by: HugeBob | last post by:
Hi All, I've got a question about Asynchronous vs Synchronous mode with the XMLHttpRequest object. What are the ramifications of using one mode vs the other? If the script uses Asynchronous mode, it sounds as if a thread retrieves the data from the supplied URL and the JS function that called the open() and send() methods continues on. Where as using Synchronous mode the method that called open() and send() waits until the data from...
by: Angus | last post by:
Hello I want to get an Ajax example working with a Perl script. I have this at the moment but nothing seems to get sent to the server self.xmlHttpReq.open('GET', 'http://myurl.com/example.pl?name=lisa', true); self.send(); But as I say nothing gets sent.
by: Michael Nemtsev [MVP] | last post by:
Hello, In the current application we have several httpmodules to process pages, and we have several pages with calls directly through the XMLHttpRequest. Now the requiremens is to detect the calls through the XMLHttpRequest and apply addional actions in httpmodule for these types of call. Because they dont use ASP.NET AJAX for this I cant use ScriptManager.IsInAsyncPostBack. Everything what comes into my my how to catch these calls is...
by: q-rious | last post by:
Hello All, I have a question regarding XMLHttpRequest. I have the following code (as part of a much larger file): function loadXMLDoc(url) { // branch for native XMLHttpRequest object if (window.XMLHttpRequest) { req = new XMLHttpRequest();
by: gradinafrica | last post by:
I'm trying to create a log out button that uses AJAX to call a php file which ends the current session: //logout.php <?php if (!session_start()); session_destroy(); //Destroys the session echo "success"; ?>
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.