I am trying to send a variable with jQuery’s getJSON function but it doesn’t seem to be going through, I am also unsure of how to get the variable I have just sent in the waiting PHP file, do I just reference it via the name I sent it as, for instance if I send a variable called 'test', can I get it like this, $_POST['test'] on the other side? or how exactly would that work?
I am trying to populate a drop down list using the method below, any advice on improving the code would be greatly appreciated!
Here is what the PHP returns:
[{"city":"One"},{"city":"Two"},{"city":"Three"},{"city":"Four"}]
jQuery:
//get the cities
$("#province").live('change', function(){
var test = $('#province').val();
//alert(test);
$.getJSON("cities.php", test, function(data){
//clean out the select list
$('#city').html('');
//run the loop to populate the drop down list
$.each(data, function(i, data) {
var city = data.city;
$('#city').append(
$('<option></option>').html(city)
);
});
});
});
PHP:
$province = $_POST['test'];
//mySQL query here
$myarray = mysql_fetch_array($query, true);
$string = explode(',', $myarray['cities']);
foreach($string as $key=>$value) {
$string[$key] = array('city'=>$value);
}
$json = json_encode($string);
echo $json;
What could I be doing wrong?
Thanx in advance!
A couple of things, first,
getJSONis a get ajax call. So, you should be expecting the data you pass usinggetJSONto end up in$_GETand obviously$_REQUEST, but not$_POST. Secondly, you have to pass an object which describes a map of data which will be reflected in the associative array,$_GET.So your code should read…
with that, you can access on PHP side as
$_GET['test']A few improvements I can give… (untested)
and php
Good luck.