Sometimes, it’s very useful and a lot cleaner to store the result of an AJAX request into a variable – that can used in your script. For instance, say you’re using some sort of calander plugin that takes an array of exluded dates. It is highly likely that these dates will come from an database. You could echo them out manually by mixing PHP, HTML and JQuery, but this is very messy.
Instead, you could create an AJAX request that queries a database for the dates and stores them in a variable. This is fairly simply when using JQuery:
$(document).ready(function() { var myAJAXVariable = (function () { var myAjaxValue = null; $.ajax({ 'async': false, 'global': false, 'url': 'ajax.php', beforeSend: function () { $('h1').css('background-image', 'url(ajax.gif)'); }, success: function (returnedData) { $('h1').css('background-image', 'none').html(returnedData); } }); return myAjaxValue; })(); });
The ajax.php file simply returns a list of comma seperated numbers from a loop – in reality this woulod be actual output from your database. The contents of ajax.php:
$values = array(); for ($i = 1; $i<11; $i++) { $values[] = rand($i, $i*23); } $data = implode(", ", $values); sleep(3); echo $data;
There is a delay of 3 seconds to simulate an intensive script – so the example doesn’t load instantly. The HTML is very basic, it only requires a single, empty h1 tag (as I’ll be loading the contents of AJAX result into it).
That’s it, the final result can be seen here and you can download the source files from here.
Nice work!
This is the only working example on the first page of google results that actually works.
You saved me a ton of time.
Thank you very much, helped a lot!