views:

420

answers:

2

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.

+1  A: 

The issue is with the php code.

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

chris
A: 

try in your php this pattern:

[
   {"text":"Google Website","url":"http:\/\/www.google.com"},
   {"text":"Yahoo Website","url":"http:\/\/yahoo.com"}
]
Reigel
That worked. Thank you.
ensnare
Then you should accept this answer by clicking the hollow check.
SLaks