I need a little help in my application design. Using Ajax I want to get some PHP resources consecutively but I don’t think if it is good to retrieve them using JQuery $.ajax method.
I think something like this means wrong design:
$.ajax({
url: SERVERURL+'index.php/home/checkAvailability',
datatype: 'text',
success: function(data){
if(data == 'unavailable'){
// do stuff
}
else{
$.ajax({
url: SERVERURL+'index.php/home/getWebTree/',
dataType: 'json',
success: function(data){
// do stuff
}
});
}
}
});
Can anybody give me a suggestion to get a better design? How can I do the same in a better way?
Thanks!
EDIT: like @arnorhs tell us, using async parameter could be a solution. But I’m still think that there are other solutions instead of using consecutive ajax calls.
EDIT2: checkAvailability and getWebTree are PHP functions using CodeIgniter that I’ve developed to get resources from an external server using Http_Request object.
function checkAvailability() {
$this->load->library('pearloader');
$http_request = $this->pearloader->load('HTTP', 'Request');
$http_request->setURL('http://myurl');
$http_request->_timeout = 5;
$http_request->sendRequest();
$res = 'available';
if (!$http_request->getResponseCode())
$res = 'unavailable';
return $res;
}
Doing the calls all the same time
If you want to do all the ajax calls at the same time, you can simply call an ajax request right after the others. You could even assign them the same success handler. If you want a more "elegant" approach, I would do something like this:
.
Do a single request
I don’t know your use case, but of course what you really should be trying to do is retrieve all the data you’re retrieving in a single request. That won’t put a strain on your server, the site/application will seem faster to the user and is a better long term approach.
I would try to combine
checkAvailabilityandgetWebTreeinto a single request. Instead of receiving the data in Javascript as text objects, a better approach would be to receive them as json data. Luckily PHP provides very easy functions to convert objects and arrays to json, so you’ll be able to work with those objects pretty easily.edit: small modifications in the PHP code now that I understand your use case better.
So something like this in the PHP/CI code:
And the Javascript code can then access those by a single ajax request:
.
Execute the requests synchronously
If you set the
asyncparameter in the $.ajax options tofalsethe functions will be made in a synchronous fashion so your code halts until execution has been completed.. or as the documentation says:See http://api.jquery.com/jQuery.ajax/