galaxyg galaxyg - 23 days ago 7
jQuery Question

jqueryui autocomplete not working/working depending on the domain identical JSONP is served from - why?

The code is below, directly taken from the jqueryui autocomplete example. The only change is that it's picking up the JSONP from my own site, except it does nothing except stay on the little spinner whilst looking for a response.

$( "#birds" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "http://www.galaxygraphics.co.uk/fresnius_jsonp.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 3,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
} );


If I change the source of the JSONP to

url: "https://jqueryui.com/resources/demos/autocomplete/search.php",

..then it's all working OK. So the question is, what's different between the JSONP served in the jqueryUI example and my own page's JSONP? Both are served as text/html mime type and I see no differences at all either in the page as displayed, the data, the source or the headers.

https://jqueryui.com/resources/demos/autocomplete/search.php, = OK
http://www.ggfxserve.co.uk/fresnius/fresnius_jsonp.php, = Not OK, even though identical.

If you want to test with the autocomplete form to see it in action (or not):-

http://www.ggfxserve.co.uk/fresnius/autocomplete.html = working
http://www.ggfxserve.co.uk/fresnius/autocomplete2.html = not working. Type "com" into either to start them off trying to autocomplete.

Answer

You can't hard code the callback in the php unless you stipulate what it is in the request.

You are outputting jQuery1124009416418827878958_1479031851542() in the php when opened directly in browser but that name is dynamically generated based on timestamps during the actual request

The norm for jsonp output would be to use $_GET['callback'] and jquery adds the query param to the url automatically when you set dataType as jsonp.

In their demo look in browser dev tools network to see the url used to confirm.

So your very basic php code would look something like

echo $_GET['callback'] . '(' . json_encode($output) .')';

I would suggest you implement CORS instead and then rely only on json being served.

The disadvantage of using jsonp is it is a script request not an XMLHttpRequest and it has error handling limitations