galaxyg galaxyg - 10 months ago 43
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: "",
dataType: "jsonp",
data: {
term: request.term
success: function( data ) {
response( data );
} );
minLength: 3,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + );
} );

If I change the source of the JSONP to

url: "",

..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., = OK, = Not OK, even though identical.

If you want to test with the autocomplete form to see it in action (or not):- = working = not working. Type "com" into either to start them off trying to autocomplete.

Answer Source

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