Reputation: 4304
I know this has been asked a million times, but it's just not working for me. I have a PHP script (get_pathway_allowed.php) which outputs the following json format when hardcoded
{"pathway_allowed":"n","comment":"one comment"}{"pathway_allowed":"y","comment":"comment two"}{"pathway_allowed":"n","comment":"comment three"}{"pathway_allowed":"n","comment":"comment four"}
Ajax script:
$('.pathway_button').click(function() {
alert(caseId + ' ' + currentLevel);
$.ajax({
type: "POST",
url: "scripts/get_pathway_allowed.php",
data: {case_id: caseId, level: currentLevel};
dataType: "json",
cache: false,
success: function(response) {
alert(response[0].pathway_allowed);
}
});
});
Now alert(caseId + ' ' + currentLevel);
shows the correct initial values of the two variables. But I'm not seeing the alert after success. If I remove dataType: "json",
I see the success alert with values undefined (to be expected...).
get_pathway_allowed.php has:
$case = $_POST['case_id'];
$level = $_POST['level'];
$query = "SELECT * FROM pathway WHERE level = '$level' AND case_fk = '$case'";
$result = mysql_query($query, $connection) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$caseData = array(
'pathway_allowed' => $row['pathway_allowed'],
'comment' => $row['comment']
);
print json_encode($caseData);
}
As I said before, hardcoding:
$case = '10';
$level = '1';
outputs the json data as above OK. What am I doing wrong?
Upvotes: 1
Views: 1053
Reputation: 117364
the creation of the JSON-string is wrong, use:
$caseData=array();
while ($row = mysql_fetch_array($result)) {
$caseData[] = array(
'pathway_allowed' => $row['pathway_allowed'],
'comment' => $row['comment']
);
}
print json_encode($caseData);
additionally there is a syntax-error:
data: {case_id: caseId, level: currentLevel};
//------------------------------------------^
the semicolon has to be a comma
Upvotes: 2
Reputation: 1258
Your json is not valid, it should look something like this:
{
"data": [
{
"pathway_allowed": "n",
"comment": "one comment"
},
{
"pathway_allowed": "y",
"comment": "comment two"
},
{
"pathway_allowed": "n",
"comment": "comment three"
},
{
"pathway_allowed": "n",
"comment": "comment four"
}
]
}
use jsonlint to validate your json.
Upvotes: 1
Reputation: 2570
Fix your JSON String:
{ "values": [
{"pathway_allowed":"n","comment":"one comment"},
{"pathway_allowed":"y","comment":"comment two"},
{"pathway_allowed":"n","comment":"comment three"},
{"pathway_allowed":"n","comment":"comment four"}]
}
Upvotes: 1