This seems simple, but I’m so new to this that I can’t get it running – even after hours of reading tutorials and examples. I want my PHP to run a query, make an array of strings, and return the array to the jQuery ajax() that called for the data. The return array should be the strings stored in the database, and look like
citiesWithBoroughs = [
"Dallas, Dallas County, Texas, United States",
"Fort Worth, Tarrant County, Texas, United States",
"El Paso, El Paso County, Texas, United States"
];
The query and array creation code are below. The query works in MySQL Workbench and returns the data I want. I have hard coded the country and state below to reduce sources of error while testing. I will replace them with “mysql_real_escape_string($countryAbbreviation)”, and so forth, when I get a controlled test working.
$return_arr=array();
$fetch = mysql_query("SELECT DISTINCT cityWithBoroughsGeonamed FROM places.boroughs
WHERE countryAbbreviation='US'
AND stateProvinceAbbreviation='NY'
") or die(mysql_error());
while ($row = mysql_fetch_array($fetch)){
$return_arr[]=$row['cityWithBoroughsGeonamed'];
}
echo $return_arr;
Currently, Firebug tells me the key/value data goes to the PHP server, but I get an empty array returned. I’ve tried several things, but get nothing or an empty array – after lots of trials.
On the JavaScript side, here is the ajax function that requests the data, and gets the returned array.
citiesWithBoroughs = function (request, response){
$.ajax({
url: "getCitiesWithBoroughs.php",
data: {stateProvinceAbbreviation: $("#hiddenState").val(),
countryAbbreviation: $('input[name=country]:checked').val()},
type: "POST",
dataType: "text",
success: function (data){
response;
}
});
What has to change to get this right? Please be specific about code. I’m pretty new to this.
echo will output a string. $return_arr is an array of strings and
echo $return_arr;will only outputArray(). I would recommend usingecho json_encode($return_arr);and handling the json encoded string in the success callback in the client side script.