I've been looking for a week now and I can't find an answer for this situation.
I request data through jsonp.
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
sync: true,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
In my server side i sent info like this:
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$html = array("Appfeed".$af."" => array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("
",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
array_push($jarr, $html);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
And it returns the data:
jQuery21007744578921701759_1395250905357({
"Appfeed0":
{
"cnty":"MEXICO",
"feed":"text",
"feedId":"201",
"nickname":"chaparra",
"state":"Tamaulipas",
"date":"27\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed1":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"198",
"nickname":"estudiante",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed2":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"197",
"nickname":"el roger",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
But when I try to loop through this in java script It just shows the last feed (Appfeed2). Also in when I print the data in console.log(). It looks like just received the last feed too.
Object {Appfeed2: Object}
1. Appfeed2: Object
1. state: "Tamaulipas"
2. date: "26/02/14"
3. feed: "Ayer fui a sacar mi licencia, sin saber manejar, no hice fila y solo me costo 200 pesos mas. Creo que sere taxista "
4. feedId: "197"
5. nickname: "el roger"
6. cnty: "MEXICO"
7. __proto__: Object
2. __proto__: Object
Any ideas? I was thinking about the way jsonp is returning the data, so I tried with square brackets, with and w/o the get callback, but it fails.
Thank you so much for your help!
You need to make sure that in your PHP code, you are only echoing out the JSON(P) once after the loop finishes. You need to build the array you want then echo it out at the end.
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$jarr["Appfeed".$af] = array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("
",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
P.S. Your AJAX call has a few too many options:
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
success: function(data) {
$.each(data, function(i, v){
console.log(i);
console.log(v);
});
}
});