18

I fairly new to JQuery and perhaps trying to achieve something that might be abit harder for a beginner. However I am trying to create an autocomplete that sends the current value to a PHP script and then returns the necessary values.

Here is my Javascript code

$("#login_name").autocomplete({
    source: function(request, response) {
 $.ajax({
     url: "http://www.myhost.com/myscript.php",
     dataType: "jsonp",

     success: function(data) {
  alert(data);
  response($.map(data, function(item) {
      return {
   label: item.user_login_name,
   value: item.user_id
      }
  }))
     }
 })
    },
    minLength: 2
});

And here is the the last half of "myscript.php"

while($row = $Database->fetch(MYSQLI_ASSOC))
{
    foreach($row as $column=>$val) 
    {
        $results[$i][$column] = $val;
    }
    $i++;
}
print json_encode($results);

Which produces the following output

[{"user_id":"2","user_login_name":"Name1"},{"user_id":"3","user_login_name":"Name2"},{"user_id":"4","user_login_name":"Name3"},{"user_id":"5","user_login_name":"Name4"},{"user_id":"6","user_login_name":"Name5"},{"user_id":"7","user_login_name":"Name6"}]

Can anyone tell me where I am going wrong please? Starting to get quite frustrated. The input box just turns "white" and no options are shown. The code does work if I specify an array of values.

UPDATE I have changed the code to and still having no luck.

$("#login_name").autocomplete({
    source: "/ajax/login_name.php",
    dataType: "json",
    minLength: 2,
    cache: false,
    select: function(event, ui) {
        alert(ui);
    }
});

Using FireFox's Web Developer tool, I am getting an error "b is null".

3
  • Just had a thought; does "myscript.php" need to send out a "JSON header" (if such thing exists)... Commented Mar 29, 2010 at 12:26
  • It appears the argument is not getting passed through the ?q= as documented??? Commented Mar 29, 2010 at 13:33
  • Now I have removed the (isset($_GET['q'])) i am getting "undefined" options in the auto complete when using $("#login_name").autocomplete({ source: "/ajax/login_name.php", dataType: "json", minLength: 2, cache: false, formatItem: function(data) { return data.user_login_name; }, formatResult: function(data) { return data.user_id; } }); Commented Mar 29, 2010 at 13:36

7 Answers 7

20

Finally found the solution that fits my needs

$("#login_name").autocomplete({
  source: function(request, response){
    $.post("/ajax/login_name.php", {data:request.term}, function(data){     
        response($.map(data, function(item) {
        return {
            label: item.user_login_name,
            value: item.user_id
        }
        }))
    }, "json");
  },
  minLength: 2,
  dataType: "json",
  cache: false,
  focus: function(event, ui) {
    return false;
  },
  select: function(event, ui) {
    this.value = ui.item.label;
    /* Do something with user_id */
    return false;
  }
});
Sign up to request clarification or add additional context in comments.

Comments

4

some suggestions:

  1. Why dataType= "jsop"? It doesn't appear to be jsonp. I think you want "json".
  2. insert a cache : false in the options, as well. This insures the request is always made, and never satisfied from browser-side cache.
  3. check if the call is going out, with something like Fiddler or Charles.
  4. does your success fn get called? You have a alert() there. Does it get invoked?
  5. if you have Firebug or the IE8 developer tools, you can put a breakpoint on the alert() to verify the value of the parameters.
  6. Why specify the full hostname in the URL? Last night I had an odd situation with autocomplete where the response was null, the empty string, when I used a different hostname for the page and the Ajax request. When I modified it to use the same hostname, the request succeeded. Actually because of the same origin policy, you should have no hostname at all in the URL for the ajax call.

1 Comment

I was using a modified version of this script jqueryui.com/demos/autocomplete/remote-jsonp.html and if i copy and paste the code, it works perfectly. Now trying to use a modified version of jqueryui.com/demos/autocomplete/remote.html
2

Yes you do need header info for your json

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); 
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); 
        header("Cache-Control: no-cache, must-revalidate" ); 
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");

and tvanfosson makes a good point abut the the plug

in anycase I don't think you make the ajax call the plugin does.

if you are infact using jquery-ui autocomple you should read over the documentation get a basic version running. your php is fine aside from the missing header data

2 Comments

You use "text/x-json" or the content-type. But I think the preferred content-type for json is "application/json" or "text/javascript". That is what jquery 1.4.2 expects when sending an ajax request for json, and that is what is being proposed as the standard.
I have added tried all the variations of these headers with no success.
2

In case anyone else needs it :

The documentation for autocomplete in jQuery UI specifies the querystring parameter to use is 'term' and not 'q'... or least it does now.

E.g. http://www.myhost.com/myscript.php?term=someToSearchFor

Comments

1

Simple Jquery ui autocomplete, for those who might need it.

//select data from the table
$search = $db->query('SELECT Title from torrents');

//then echo script tags and variables with php
<?php echo '<script type="text/javascript">
 $(function() {
  var availableTags = [';
 foreach ($search as $k) {
  echo '"'.$k['Title'].'",';
}
  echo '];
$( "#tags" ).autocomplete({
  minLength:2, //fires after typing two characters
  source: availableTags
});
});
</script>';

 ?>

your html form

<div id="search">
<form id="search-form">
<input id="tags" type="text" />
<input type="submit" value="Search" />
</form>
</div>

Comments

0

A JSON strcuture is a flat string, while map expects an array or array like structure. try json decode on the string before using map.

1 Comment

btw, you will need to either add json or jquery json plugins to get it decoded ( as far as i know). some pointers here: groups.google.com/group/jquery-en/browse_thread/thread/…
0

I had a problem like you too. And now I fix it. The problem is my json that return from my server contain a syntax error.

In http://api.jquery.com/jQuery.getJSON/ tells that if there are some error in JSON, it will fail silently. The JSON must match the JSON standard here http://json.org/ .

For my error is my string in JSON is wrapping in only one quote. But the JSON standard accept only string that wrap in double quotes.

eg. "Hello World" not 'Hello World'

When you fix it you can set the source as string URL. The term will be in "term" query string. And it works!!

1 Comment

Not sure it's the same problem. The JSON that @bigstylee shows have double quotes and not single.

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.