1

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.

2
  • 1
    what's with {ldelim} and {rdelim} in the first code snippet? Commented Jan 27, 2010 at 7:12
  • Sorry -- should read { and } ... it was a copy and paste from Smarty. Fixed. Commented Jan 27, 2010 at 7:22

3 Answers 3

1

The issue is with the php code.

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

Sign up to request clarification or add additional context in comments.

Comments

1

try in your php this pattern:

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

1 Comment

Then you should accept this answer by clicking the hollow check.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.