Want to stay up to date? Then why not subscribe to the RSS feed?

Or subscribe by email
Interested in Advertising? I sometimes have 125x125 banner slots available for only $40pcm. Reviews only cost $40 too.
I'm nearly fully booked so get in touch now
Recent Comments
Posted on Saturday 22nd of December 2007 at 12:10 in Tutorials

Multiple AJAX responses with 1 request (mootools and PHP)

It's a common problem and I started thinking about solutions after reading this 9rules note. How do you manage multiple return AJAX statements in an efficient manner? The synopsis of my thinking is in the note but I'll go into a bit more detail here.

Supposing you have a website that needs multiple regions updating through an AJAX call, how do you manage multiple requests? It's easy enough making an AJAX request and getting a response (using Javascript frameworks like mootools or scriptaculous) but they're normally only geared up for single requests. So if you've got multiple things to do, how can you manage it without having to make separate requests?

Why separate requests aren't great
If you want to update three separate regions, then using separate requests means that you're waiting longer. 3 times you make a request and 3 times you wait for a response, rather than making 1 request, waiting for 1 response and processing the result. So here is how I'd consolidate everything into the one request:

Supposing I had a website as per the diagram below, but wanted to update all 3 content regions on one click, using one request:

3 content regions

The basic logic is to return all 3 parameters using a suitably rare delimiter. Let me explain using code and examples.

See the demo first

Code examples
It's worth noting that I'm using the Mootools framework to handle the XHR requests because it simplifies things an awful lot - writing XHTTP requests manually is a pain. So let's look at the HTML I'm using: Note the title attributes on the anchor tags, these are useful because using them I can identify which anchor tag was clicked, without needing to have an ID on each. Ideally you'd use the href so that you're just hijacking the underlying PHP using Javascript, but this is just a quick and dirty example.

Let's look at the javascript needed to interact with that: So all I'm doing there is using the GET method to send data to my "process.php" file. The significant part to note is the myString.split function - because the PHP is going to return a long string containing 3 different sets of content, it's important to use a really unique delimiter to identify when one record stops and another starts. I'd have to be something really unusual to use ###RAWR### in my content (besides here, obviously).

I know I'm only going to get 3 responses back which makes life easy, because we're only updating a finite number of divs with content.

So let's look at the PHP used in "process.php" as this is what gets returned: All the above code is doing is checking the querystring that was passed through in the AJAX call and changing the contents of the array accordingly. Clearly you'd do something more useful than this - your array is probably going to be populated by doing a MySQL query or something, but purely for this example I'm using rather inane fake content like "pigeon". I then iterate through the array and apply the unique delimiter to the end of each row. Simple. When I return this to the Javascript I can then split the three records off from one another and populate the divs accordingly.

And there you have it, really simple stuff. It's a really dirty, horrible and probably an overly stupid way to manage multiple AJAX requests but it's how I've solved the problem. I don't see it being a massive problem provided you're dealing with the same kind of data; otherwise you'd be better making separate requests. PHP is doing all the work anyway.

See the demo

Enjoy this article? Why not subscribe to the full RSS feed?


Did you like this article?
If you liked this article then please show your support and give me a Digg. If you'd like to get in touch with me, email me at steven.york@seopher.com
Want to stay updated?
Sign up to RSS updates by email (or subscribe to the full RSS feed)

Enter your email address:


Add a comment






Comments

Showing most recent 17 of 17 comments

For those who like tight data structure, or who cannot wrap their head around JSON, it’s really not that bad.

Send your response from the PHP script as a JSON-encoded array:

$one = ’This’;
$two = ’That’;
$three = ’The other’;

echo json_encode( array(
’one’ => $one,
’two’ => $two,
’three’ => $three,
) );

Then simply decode that string into an object using mootools’ JSON class:

onSuccess: function( response ) {
var response = JSON.decode( response );
alert( response.one );
alert( response.two );
alert( response.three );
}

Simple as that!
Keith
good
nik
Thanks, that the better post to explain a ajax request with mootools.
Bob
Thank You!
I was looking for the solution like that.
Vaidas
Yeah! Found what I was looking for... Thank you so very much. This really helped!!!!
Sandro44m
There will be a problem when you click the link twice T_T the second event cant be active
hitori_vodanh
Hi,

i have another and i think better solution for this Problem.
With your code i must work with the XHR Class and its a Problem to eval Scripts in the response.

Here my solution:

var myAjax = new Ajax(’kalkulator.php’, {
method: ’post’, // Get also works fine
evalScripts: false, // Must be false, is evaluated later
evalResponse: false,
data: $(’kform’).toQueryString(), // Post data. Use here a form or what ever
onComplete: function(){
var myString = this.response.text;
var myStringArray = myString.split("");
$(’content_left’).empty().setHTML(myStringArray[0]);
$(’content_right’).empty().setHTML(myStringArray[1]);
this.evalScripts(); // eval starts after placing the code on the right place
},
}).request();


Christian Sädtler
I found this article really useful thanks!

I read some of the comments but i can’t get my head round json so i found your method much easier.
Rich
Maybe this will help some people, it will allow you to choose which div you want to update via PHP callback.

[code]
window.addEvent(’domready’, function()
{
$(’container’).getElements(’a’).addEvent(’click’, function(e){
e = new Event(e).stop();
var querystring = this.title;
var myXHR = new XHR({
method: ’get’,
onSuccess: function(){
//Get the response from PHP
var myString = myXHR.response.text;
//Split the array using |
var myStringArray = myString.split("|");
//Looping through the array to find the div and its content
var i=0;
for(i=0; i < myStringArray.length; i+=2){
$(myStringArray[i]).innerHTML = myStringArray[i+1];
}
}
}).send(’data.php’,’page=’+querystring);
});
});

[/code]

[code]
//your PHP can be this simple

echo "div1|Div 1 content goes here.|div2|Div 2 content goes here|div3|Div 3 content goes here.";
[/code]
Epik
Wow, those are some pretty harsh comments. I think this tutorial is a great starting point for those who may not _need_ JSON or just have a really simple task they want to accomplish. Thanks for the ideas.

As an aside note, I love the style of your code samples.
S-Anarchy
As the previous posters have indicated... JSON. yes.
take a look and you’ll see its far more powerful.
but at the same time you acknowledged your method was "dirty, horrible, and probably overly stupid" so you get the pity vote. :)

cheers
Paul Irish
Nice Commenting style in your Blog by the way..
Bijay Rungta
And by what logic do you call this "multiple responses"? There is only one response!
I bet you haven’t heard of JSON, huh?

Exactly...

So you think AJAX is only about getting a response with the html content of the regions whose display content you want to changeby simply using blahblah.innerHTML = blahResponse.responseText

There is a lot more than this.
You can have the response be in XML or JSON with a lot of information chunks with meaningful data.

http://lamp-ajax.blogspot.com
http://bijayrungta.blogspot.com
Bijay Rungta
The PHP code could be refactored... I know it wasn’t the purpose of this post, but good php code would have been a good thing...
Tim
And by what logic do you call this "multiple responses"? There is only one response!
I bet you haven’t heard of JSON, huh?
Nikola
Thanks for that Mike, it’s now resolved. Just shows why you should proof read your content.
Seopher
The process.php code is cut off in the middle of the for loop.
Mike