I'm loading a JSON array from an external Domain. I have gotten this to work correctly yet I am still having problems actually showing any of the results. Using examples and other question/answers I have gotten as far as an attempt of displaying the results apparently being made, but ending in an uncaught error:
Uncaught TypeError: Cannot read property 'label' of undefined
Code snippet:
$('#citySearchBox').autocomplete({
source: function(request, response){
$.ajax({
url: "/api.php",
data: {action: "search", input: request.term},
dataType: "jsonp"
});
response(function(data){
return $.parseJSON(data);
});
},
minLength: 3
});
Server Response as seen in debugger:
[{"id":"1.3.0.0.0.0","label":"Berlin (10115)","value":"index.php?action=city&city=1.3.0.0.0.0"}, etc...]
As you can see I have attempted to parse the string into a JS Object, with shown method and also tried JSON.parse(data)
.
If I've made a mistake earlier than the "response" part but somehow managed to half-way bodge it please point out my mistakes.
EDIT:
I've changed the code after Bradys suggestion, but I seem to be doing something wrong with the syntax, as putting a break-point inside of the response function nothing is stopped.
This is the updated response function:
response( function(data){
var items = data.text().slice(1, -1).split(',');
for(i=0; i < (items.length - 3); i=i+3)
{
items[i] = $.parseJSON(items[i]) + ','
+ $.parseJSON(items[i+1]) + ',' + $.parseJSON(items[i+2]);
}
return items;
});
Case closed, never actually got JSONP to work, but the situation changed and was no longer reliant on cross-domain communication.
For anybody interested working code is as follows:
$('#searchBox').autocomplete({
source: function(request, response){
$.ajax({
type: "GET",
url: "api.php",
async: true,
data: {action: "search", input: request.term},
success: function(data){
var items = $.parseJSON(data);
response(items);
}
});
},
select: function(event, ui){
$('#searchBox').val(ui.item.value);
window.location.href = ui.item.url;
},
minLength: 2
});