When I try to parse a response from an AJAX request as JSON, I get [object, Object] values instead of the actual ones returned before parsing the response. What could I have done wrong?
I have one script named "apply.php" which has the a short application and an AJAX request called when the user selects a town. There is another script named "suburb.php" which retrieves stored suburbs in the database that are under the selected town. The second script is called when the users selects/changes a town.
In the "apply.php" script I have a JavaScript alert that display the response, which I then parses as JSON. After passing the response, [object, Object] is returned instead of the actual values, thus disabling me from reading the JSON key values.
Using the values without parsing them does not help either. I tried checking for question that relate to my problem without any luck.
Your assistance will be greatly appreciated.
apply.php
<?php
$dbcon = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Accomodation Application</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<style>
form div {
margin-bottom: 20px;
}
</style>
<body>
<div>
<div>
<form>
<p><a href="http://localhost/testwork/">Refresh</a></p>
<div><label for="applicant-name">First Name</label><br /><input type="text" name="name" id="applicant-name"></div>
<div><label for="applicant-surname">Surname</label><br /><input type="text" name="surname" id="applicant-surname"></div>
<div><label for="applicant-identity">Smart ID Number</label><br /><input type="text" name="surname" id="applicant-identity"></div>
<div id="town">
<label for="applicant-town">Town</label><br />
<select name="town" id="applicant-town"><option value="0">-- Select Town --</option>
<?php
$towns = mysqli_query($dbcon, "SELECT town_id, town_name FROM towns");
while($town = mysqli_fetch_array($towns)){
$town_id = $town['town_id'];
$town_name = $town['town_name'];
echo("<option value=\"$town_id\">$town_name</option>");
}?>
</select>
</div>
<div id="suburb">
<label for="applicant-suburb">Suburb</label><br />
<select name="suburb" id="applicant-suburb">
<option value="0">-- Select Suburb --</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
</div>
</div>
<script>
$(document).ready(function(){
$('#applicant-town').change(function(){
var suburb_town = $(this).val();
$.ajax({
type: "GET",
url: "suburbs.php",
data: {town: suburb_town}
})
.done(function(data){
alert(data);
var burbs = JSON.parse(data);
alert(burbs); // e.g. [{"1":"Halfway House"},{"2":"Noordwyk"},{"3":"Vorna Valley"}]
$(burbs).each(burbs, function(key, value){
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
});
})
.fail(function(){
alert('There is an error somewhere.');
});
});
});
</script>
</body>
</html>
suburbs.php
<?php
$dbcon = new mysqli (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_GET['town'])){
$town_suburbs = array();
$town_id = htmlspecialchars($_GET['town']);
$suburbs = mysqli_query($dbcon, "SELECT suburb_id, suburb_name FROM suburbs WHERE suburb_town = $town_id");
while($suburb = mysqli_fetch_array($suburbs)){
$suburb_id = $suburb['suburb_id'];
$suburb_name = $suburb['suburb_name'];
$town_suburbs[] = array($suburb_id => $suburb_name);
}
echo json_encode($town_suburbs);
}
?>
So first off from the comments you can see what the issue is. However, you may want to use your "id" for something so with that in mind you could do the following.
$town_suburbs[] = array($suburb_id => $suburb_name);
You could change that to
array_push($town_suburbs, array("id" => $suburb_id, "name" => $suburb_name));
Then on your javascript side...
$(burbs).each(burbs, function(key, value){
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
});
That could change to:
$(burbs).each(function(){
$('#applicant-suburb').append('<option value="'+ this.id +'">'+ this.name +'</option>');
});
Perhaps, it was already saved as [Object Object]? Ensure that,
to decode a JSON string, use JSON.parse()
to encode a JSON string, use JSON.stringify
Hope this helps.
Why not use dataType: "json" in your statement ajax?
$.ajax({
type: "GET",
url: "suburbs.php",
data: {town: suburb_town},
dataType: 'json'
})
Thus instead of making an "alert ()" you must make a "console.log" and analyze the content through the Javascript console your browser.
The Alert feature only shows "String" and therefore when attempting that shows you the content. The representation of an object in string is [object]. Therefore instead of console.log occupies alert ().
update: You can use alert (JSON.stringify (data)) to display the string in a alert.
update2: Your code will looks
$.ajax({
type: "GET",
url: "suburbs.php",
data: {town: suburb_town},
dataType: 'json'
})
.done(function(data){
console.log(data)
});
})
If your "E.G." is correct, then you are not looping (in javascript) in the correct way.
This:
$(burbs).each(burbs, function(key, value){
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
});
Should not work, because you have to loop an array of objects, therefore you first have to loop the array and, then, the objects:
for (var i = 0; i < burbs.length; ++i) {
$.each(burbs[i], function(key, val) {
$('#applicant-suburb').append('<option value="'+key+'">'+val+'</option>');
});
}
According to your example, you can check this fiddle: http://jsfiddle.net/5yaj7La0/2/
As long as your current output has this structure:
[{"1":"Halfway House"},{"2":"Noordwyk"},{"3":"Vorna Valley"}];
You DON'T need to change your PHP code but if the output is different from that (it shouldn't, though), you may need to change your PHP code too.
HTML output :
(output is related to the fiddle, feel free to edit the names and tag and whatever, the important thing here is the Javascript).
Can the problem be with the fact that you are missing a header() statement in your suburb.php file?
Something like
If you get [Object object]
by doing :
var burbs = JSON.parse(data);//alerting this will definitely present [Object object]
Then everything seems to be fine.
You are parsing the data and this will be converted to a json object.
If you want to view the response data use :
var burbs = JSON.stringify(data);//converts the object to a string
alert(burbs);
Also probably you want to get the values by accessing the keys of each object within the object array:
//lets imagine this is our response data, which can also be the response data you parsed with JSON.parse(data);
var data = [{"1":"Halfway House"},{"2":"Noordwyk"},{"3":"Vorna Valley"}];
function iterate(data)
{
for(var i=0;i<data.length;i++)
{
for(var i=0;i<data.length;i++)
{
for(var key in data[i])
{
var value = data[i][key];
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
}
}
}
}