Reputation: 31
Haven't found this exact situation on here, so I figured I'd ask. I have some JavaScript that, using AJAX, is attempting to call a PHP file, execute the PHP script, and return a concatenated PHP variable through xmlhttp.responseText, then alert that response.
JS
function queryDB() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","php/location.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
PHP
<?php
$con = mysql_connect("<THIS DATA HIDDEN FOR SECURITY PURPOSES, IT IS CORRECT");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gpstracks", $con);
$bus = $_GET['bus'];
$query = "SELECT lat, lon from tracksarchive where runnerid = '$bus' ORDER BY time DESC LIMIT 1;";
$latlon = mysql_query($query);
while ($row = mysql_fetch_array($latlon, MYSQL_ASSOC)) {
$lat = $row['lat'];
$lon = $row['lon'];
}
$result = $lat . ", " . $lon;
echo $result;
mysql_close($con);
?>
Yes, I know that mysql_ has been replaced by mysqli_, I'll deal with that later. When I execute the PHP on its own (using a form submit) - it displays the correct values from the table, but when I alert the xmlhttp.responseText - I only get the comma and space - no passed variables. Any idea what I'm doing wrong? Help is much appreciated.
Sidenote: I know the preferred method for AJAX calls these days is jQuery - but a component of the page this JavaScript is on doesn't function when I use jQuery.
Upvotes: 3
Views: 5367
Reputation: 6711
As you send request by GET
method, you need to manually add the parameter bus
to the URL. So, rewrite
xmlhttp.open("GET","php/location.php",true);
to
xmlhttp.open("GET","php/location.php?bus=value",true);
Upvotes: 1
Reputation: 66404
when I alert the
xmlhttp.responseText
- I only get the comma and space - no passed variables
You're not performing your GET properly; in your JavaScript you have
xmlhttp.open("GET","php/location.php",true);
i.e. you performed a GET request without a URI query string.
In your PHP you have
$bus = $_GET['bus'];
i.e. you're GETting this data from the URI query string, except none was passed, so this will be empty, so
$query = "SELECT lat, lon from tracksarchive where runnerid = '$bus' ORDER BY time DESC LIMIT 1;";
doesn't work as expected.
You really wanted to do something like
xmlhttp.open(
"GET",
"php/location.php?bus="+window.encodeURIComponent(foobar),
true
); // foobar your value for `bus`
Further, you'll need to do some server-side sanitisation of $bus
, as it stands you're open to SQL injection.
Upvotes: 3