I have a JavaScript function that is being called. I need to have it call a PHP function and return a true/false.
The script with the function is in the file /db/cancel_hike.php
My current JS looks like this:
function uncancelHike( hike_id )
{
//var url = "/db/cancel_hike.php;
var success = null;
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.open("GET", url , true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlDoc = request.responseXML;
// obtain the array of markers and loop through it
markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
// obtain the attribues of each marker
success = markers[i].getAttribute("success");
if ( success == "true" )
{
document.getElementById("success").style.display = 'block';
document.getElementById("warning").style.display = 'none';
document.getElementById("error").style.display = 'error';
}
if ( success == "false" )
{
document.getElementById("success").style.display = 'none';
document.getElementById("warning").style.display = 'none';
document.getElementById("error").style.display = 'block';
}
}
}
}
request.send(null);
return false;
}
What I am having trouble with is:
- How to call an actual function in the PHP script?
- Do I absolutely need to have some XML returned? Or is there a way to just get back the returned value?
- I am using YUI JS library. Do I need to make some calls to it, or is it not necessary in this case?
Well, you don’t call the actual function. What you want to do is pass variables using GET, that is, by appending them to the URL like
file_name.php?var1=this&var2=thatto pass var1 of “this” and var2 equaling “that.” You retrieve them in the PHP file with$_GET['this']and$_GET['that']. Whatever PHP outputs to the page viaecho,print_r, etc. is then sent back in a request object as part of itsresponseTextproperty.You just set
urlinrequest.opento a URL on your site. For example, in your .js file:And in your .php file:
Note that that will just return a string value to
request.responseTextof false, thus you could do this:You do not need it to be XML, especially as it looks like you’re not really using the loop (the same three DOM elements are being assigned values each time).
And honestly, for AJAX I’d recommend using a framework like jQuery (or YUI, although I don’t find its AJAX stuff as intuitive). Your entire code would look like this:
IMO things like jQuery’s
$.ajax($.getis a specialized form of$.ajax) make this stuff much easier to read and debug.jsFiddle Example