I'm trying to implement a live search on my photos site using jQuery and the autocomplete plugin. Everything works when I specifiy the data locally:

var data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ];

However when I move this to PHP, jQuery is unable to parse the results properly. I'm really not sure what's going on here. My current code is below:

var data = '/livesearch'; 
$("#aut_field").autocomplete(data, {
  formatItem: function(item) {
    return item.text;
}).result(function(event, item) {
  location.href = item.url;

And my PHP script prints a multidimensional array in the following format:

{"1":{"text":"Google Website","url":"http:\/\/"},
 "2":{"text":"Yahoo Website","url":"http:\/\/"},}

However when I do alert(item.text) the variable says undefined.

If I do alert(item) I see the entire string as outputted by PHP.

I tried playing around with eval() but I'm not sure where to put it or how to get JS to actually interpret the data. Thanks for your help. Sample code specific to my implementation is appreciated.

Was it helpful?


The issue is with the php code.

Your job is to mimic the strcuture of the working javascript array. See php's json_encode()


try in your php this pattern:

   {"text":"Google Website","url":"http:\/\/"},
   {"text":"Yahoo Website","url":"http:\/\/"}

And your PHP script return a multidimensional array/object mix. If you insist (you blow up your var with several "text:" amd "url;") it shou1ld be:

[[{"text":"Google Website","url":"http:\/\/"}],[{"text":"Yahoo Website","url":"http:\/\/"}]]


var x=[["Google Website","http:\/\/"],["Yahoo Website","http:\/\/"]];

If you want to jump to Yahoo Website: var url=x[1][1];


var x={"Google_Website":"http:\/\/","Yahoo_Website":"http:\/\/"};

If you want to jump to Google_Website: var url=x["Google_Website"];

My tip: visit enter link description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow