Question

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:

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

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

{"1":{"text":"Google Website","url":"http:\/\/www.google.com"},
 "2":{"text":"Yahoo Website","url":"http:\/\/yahoo.com"},}

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?

Solution

The issue is with the php code.

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

OTHER TIPS

try in your php this pattern:

[
   {"text":"Google Website","url":"http:\/\/www.google.com"},
   {"text":"Yahoo Website","url":"http:\/\/yahoo.com"}
]

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:\/\/www.google.com"}],[{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}]]

Better:

var x=[["Google Website","http:\/\/www.google.com"],["Yahoo Website","http:\/\/yahoo.com"]];

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

Or:

var x={"Google_Website":"http:\/\/www.google.com","Yahoo_Website":"http:\/\/yahoo.com"};

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
scroll top