Monday, December 4, 2023
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  176] [ 3]  / answers: 1 / hits: 17707  / 13 Years ago, wed, march 23, 2011, 12:00:00

I'm making an ajax call using jQuery as below.



$.ajax({
type: POST,
url: proc.php,
dataType: 'json',
data: dataString,
cache: false,
success: function(data){
alert(data.vote[0].line); //Where error shows
}
});


The php page returns echo json_encode($string); which is like



{ 'vote' : [{ 'line' : 'newline1', 'up' : '0', 'down' : '1'},
{ 'line' : 'newline2', 'up' : '4', 'down' : '1'}
]}



When I run it, an error comes up saying



Uncaught TypeError: Cannot read property '0' of undefined on the line commented above in the ajax call



Can anyone help me point out where am I doing it wrong??



UPDATE:



the variable $string is generated as below



    $comma = ,;
$success = mysql_query($query, $connection);
while($row = mysql_fetch_array($success)){
$voteUp = $row['voteup'];
$voteDwn = $row['votedwn'];

$vote .= $comma . { 'line' : '{$row['entryid']}', 'up' : '{$voteUp}', 'down' : '{$voteDwn}';
$comma = ,;
}
$string = { 'vote' : [ . $vote . ]};
echo json_encode($string);

More From » jquery

 Answers
132

Instead of writing a jsoned string with PHP, use an array. json_encode() will do the magic



$return = array();

$success = mysql_query($query, $connection);
while ($row = mysql_fetch_array($success)) {
$return['vote'][] = array(
'line' => $row['entryid'],
'up' => $row['voteup'],
'down' => $row['votedown'],
);
}

echo json_encode($return);

[#93124] Monday, March 21, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayla

Total Points: 14
Total Questions: 96
Total Answers: 123

Location: Greenland
Member since Fri, Jul 31, 2020
3 Years ago
jayla questions
;