I am trying to populate a div using ajax.Here goes the code
$.ajax({
url: "/assets/location.php",
//dataType:"json",
success: function (result) {
alert("hello");
$.each(result, function (i, val) {
alert("hello");
alert(val.title);
});
}
});
server
<?php
require_once 'include.php';
$db = connect_db();
$query = 'CALL get_location()';
$result = mysql_query($query, $db) or die(mysql_error($db));
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row);
}
echo(json_encode($data));
?>
Everything works fine but when I uncomment dataType:"json" script stops executing success function. Please point out the errors.
-
1Is your json formatted correctly? When you add dataType:json, success callback is not called when there is an error in parsing the response. And also you wont need JSON.parse , jquery will do it automatically for you.Ananth– Ananth2015年02月07日 11:36:12 +00:00Commented Feb 7, 2015 at 11:36
-
I am new to web development so I don't know it well.Read somewhere that I should use JSON.parse to make code work in chrome :( :(Piyush Khandelwal– Piyush Khandelwal2015年02月07日 11:40:35 +00:00Commented Feb 7, 2015 at 11:40
-
Thats right, you will need JSON.parse when you dont have dataType: json. But when you have it jQuery will automatically parse the json response and pass the JSON object to your success callback.Ananth– Ananth2015年02月07日 11:41:55 +00:00Commented Feb 7, 2015 at 11:41
2 Answers 2
Your success function includes the expression JSON.parse(result).
With dataType:"json" uncommented, jQuery automatically json-decodes the data.
Therefore, JSON.parse(result) will try to decode something that's already decoded.
I'm guessing you get a parse error. Check your console.
Comments
Without dataType:'json' option, your code should be.
$.ajax({
url: "/assets/location.php",
success: function (result) {
alert("hello");
//data is not parsed, so you have to explicitly parse to json
$.each(JSON.parse(result), function (i, val) {
alert("hello");
alert(val.title);
});
}
});
With dataType:'json' option, your code should be.
$.ajax({
url: "/assets/location.php",
dataType:'json',
success: function (result) {
alert("hello");
//result is already parsed to json (by dataType option),
//So no need to parse again.
$.each(result, function (i, val) {
alert("hello");
alert(val.title);
});
}
});