0

I have to read and display json formatted results in my app. I am forced to use JSONP at client side due to same origin policy. But it displays null

Please let me know where I am going wrong and it displays null. Any help is appreciated

PHP code at server side

while ($r = mysql_fetch_assoc($result))
{
    $rows[] = $r;
}
echo json_encode($rows);

JSON output I receive from PHP code above

[
    {
        "a_name": "affles",
        "bname": "bua",
        "c_number": "10101010",
        "dateandtime": "2013-11-30 17:50:04"
    },
    {
        "a_name": "affles",
        "bname": "bua",
        "c_number": "10101010",
        "dateandtime": "2013-11-30 17:50:04"
    },
    {
        "a_name": "anan",
        "bname": "nesh",
        "c_number": "2017439441",
        "dateandtime": "2013-12-04 17:50:04"
    }
]

Client side code using JSONP but still returns null. Using JSONP due to same origin policy

<script>
(function() {
  var flickerAPI = "http://apip.com/results.php?jsoncallback=?";
  $.getJSON( flickerAPI, 
    (function( data ) {
      $.each( data.items, function( index, value ) {

$('<li>' + value.a_name + '</li>').appendTo('#groups');

      });
    });
})();
</script>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user3050862
  • 23
  • 1
  • 5

1 Answers1

0

The php output needs to wrap the array in the callback function, as described here: https://stackoverflow.com/a/6809069/117314

The call to http://www.write-about-property.com/jsonp.php?callback=jQuery16206784670623019338_1387584503108&firstname=Jeff&_=1387584503108

writes in output:

jQuery16206784670623019338_1387584503108({'fullname' : 'Jeff Hansen'})

Output needs to get the jsoncallback query parameter value (or just "jsoncallback" if not provided) like:

jsoncallback([
    {
        "a_name": "affles",
        "bname": "bua",
        "c_number": "10101010",
        "dateandtime": "2013-11-30 17:50:04"
    },
    {
        "a_name": "affles",
        "bname": "bua",
        "c_number": "10101010",
        "dateandtime": "2013-11-30 17:50:04"
    },
    {
        "a_name": "anan",
        "bname": "nesh",
        "c_number": "2017439441",
        "dateandtime": "2013-12-04 17:50:04"
    }
]);

I personally prefer to add a simple test before calling the function:

if(jsoncallback) jsoncallback([,,,]);

Edit:

An other good explanation about how works JSONP: https://stackoverflow.com/a/2067584/117314

Community
  • 1
  • 1
Loic El Thesea
  • 704
  • 7
  • 17
  • I tried modifying server side code from echo json_encode($rows) to echo $_GET['jsoncallback']."(".json_encode($rows).")" but still result is same. Can you please specify where exactly do I need change in my code. Is it in server side or client side? – user3050862 Dec 21 '13 at 00:53