Retrieve JSON GET data with Javascript/JQuery

It seems that this service is not correctly wrapping the JSON object in parentheses so it doesn't work as JSONP.

See: http://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST

It returns:

TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]

while it should return:

TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);

You won't be able to use it because it is not valid JSONP.

UPDATE:

Answering more info from the comment - if you control the server-side script then try changing:

while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);

to:

while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

and see if that works.

UPDATE 2:

Answering another comment. Do you actually initialize the output variable? For example with something like this at the beginning:

var output = $('#place').append('<div/>');

Do you actually call your results function? It must be called with:

results();

or registered somewhere as an event handler, using the jQuery way:

$('form').submit(results);

but then add:

return false;

to the end of the results function to prevent the page from being reloaded.

See this demo: http://jsbin.com/uziyek/1/edit - it seems to work.

Another problem:

There seems to be another problem with your code, that the area=AB12 parameter is hardcoded into your URL. What you should do instead is get the value from the form and send that.


You implemented JSONP incorrectly. You need to generate a function call, i.e. the response should be foo(<json here>); not foo<json here>.

It is trivial to fix:

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

Another problem is that you are not preventing the form submission, i.e. when you submit the form, the page refreshes. You have to prevent that. Better bind the event handler with jQuery and don't use inline event handlers:

<form id="myForm">

and

$(function() {
    $('#myForm').submit(function(event) {
        event.preventDefault(); // <-- prevent form submission
        // Ajax call here
    });
});

DEMO