I'm struggling to make an Ajax function return a true or false value for validation purposes. The other function needs to receive this value to determine the next steps.
I'm certain I've accomplished this before, but for some reason, it's not working now. I've experimented with synchronous and asynchronous calls, placing the return statement inside and outside the onreadystatechange function, but nothing seems to work.
Here is the Ajax code:
function saveBooking(){
var service_ids=document.getElementById("allservice_ids").value;
var provider_ids=document.getElementById("allprovider_ids").value;
var chosen_time=document.getElementById("chosen_time").value;
var chosen_date=document.getElementById("chosen_date").value;
var message=document.getElementById("message").value;
var parameters="service_ids="+service_ids+"&provider_ids="+provider_ids+"&time="+chosen_time+"&date="+chosen_date+"&you=<?php echo $_SESSION['user_mail']; ?>&message="+message
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","include/save_booking.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var yesorno=xmlhttp.responseText;
if(yesorno=="ok"){
return true;
}
else{
document.getElementById("booking_error").innerHTML = xmlhttp.responseText;
return false;
}
}
}
xmlhttp.send(parameters);
}
Currently, the save_booking.php file only contains <?php echo "ok"; ?>
, simplified for testing purposes.
Can someone guide me on how to resolve this issue? When I try the following in the other function:
if(saveBooking()){
alert(saveBooking());
}
It only alerts 'undefined'.
Please keep in mind that I am not well-versed in jQuery, so suggesting 'use jQuery' would not be helpful for me.