Greetings,
I’ve been with this about 1 or 2 hours and it seems I cannot find the error in this function I’ve created to check the availability of something in a Database through jQuery and Ajax.
I’m calling the function with this link for test purpouses since I were unable to catch any errors before.
<a href="#" onclick="availability_check("Despacho", "22/05/2011","12:30", "12:45")">TEST</a>
And the code of the Function is the following:
function availability_check(location, date, from, to){
var check = 'location='+ location + '&date='+ date + '&from=' + from + '&to=' + to;
$.ajax({
type: "POST",
url: "check-availability.php",
data: check,
cache: false,
success: function(response){
var available = response;
}
});
return available;
}
Declared just under the document_ready function.
Could someone smarter than me tell me what’s wrong? Firebug just says:
3
syntax error
[Stop in this error] availability_check(
You have three problems there. First of all, you have quotes inside the
onclickattribute. Browsers will think you want to end the attribute, not start a JavaScript string. Try using'instead of".The second problem is that you’re declaring
availableinside a closure. When you’re back inavailability_check,availablewill be out of scope. Movevar availableto above$.ajaxand change what’s currentlyvar available = response;to justavailable = response;.The third problem is it seems you don’t understand asynchronicity.
$.ajaxwill be called, starting the request, but the request won’t finish immediately. It will just continue toreturn available;before the request has completed. Then, once it has completed, it will setavailable, but by then it’s too late. To fix this, addasync: falseas another option to$.ajax.