1

Been trying to cook up some JSONP to get around Cross Domain issues. Used answer here: Basic example of using .ajax() with JSONP?

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

But not getting the desired result. My code:

jquery

var url = "http://wplivestats.com/stats/jsonp.php?callback=?";

$.getJSON(url, function(result){
   //response data are now in the result variable
   console.log(result);
});

php

<?php 

include('init.php');
$pubid = $_REQUEST['pid'];

date_default_timezone_set ( 'America/New_York' );

$time =  date('Y-m-d H:i:s',time()-$polling_minutes*60);
$count = $conn->prepare("select distinct ip from stats where timestamp >= '$time' AND Pubid = '$pubid'");
$count->execute();
$users['users'] =  $count->rowCount();
echo "jsonCallback ( [";
echo json_encode($users);
echo "] )";
?>

The Error:

ReferenceError: jsonCallback is not defined
jsonCallback ( [{"users":0}] )

Where am I going wrong?

Community
  • 1
  • 1
NotaGuruAtAll
  • 503
  • 7
  • 19
  • You're not passing `pid`, yet it seems like you're expecting it, and `$users` isn't defined – adeneo Apr 14 '15 at 19:42

1 Answers1

2

The problem is in your PHP script. When you do a request using jQuery the question mark in the url will be replaced with a dynamic function name.

On the PHP side you need to use this dynamic function name to wrap your data instead of using "jsonCallback".

Your PHP code should look like this:

echo $_GET['callback'] . "(" . json_encode($users) . ")";
Wim Mostmans
  • 3,485
  • 1
  • 20
  • 20
  • One question though. How do I use the data that is returned? It shows as an object but if I try result.users I get 'undefined' – NotaGuruAtAll Apr 14 '15 at 19:54