views:

134

answers:

2

I'm trying to get auto-complete working with a simple application that I'm building. Here is my code so far:

gMeds = new Array();

$(document).ready(function(){   
    var autoComp = setUpAutoComplete();
    if(autoComp) {
     $("#med").autocomplete(gMeds);
    }
    else {
     alert('Autocomplete unavailable');
    }

});

function setUpAutoComplete() {
    $.ajax({
     url: "ajax-getAllMeds.php",
     async: false,
     type: "GET",
     dataType: "text",
     success: function(result){
      gMeds = JSON.parse(result);
      return true;
     },
     error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert(textStatus);
      return false;
     }
    });
}

The source of "ajax-getAllMeds.php" produces valid JSON (as verified by http://www.jsonlint.com/).

The JSON produced is

{
    "meds": [
        {
            "name": "ace"
        },
        {
            "name": "danger"
        }
    ]
}

What I'm trying to accomplish is turning my JSON into a javascript array and then using that array as the basis for my pool of words to "autocomplete from". Am I way off? I'm running into various problems.

A: 

The first thing you should try is this:

gMeds = JSON.parse(result).meds;

You should also move the code into the success method.

$(document).ready(function(){   
    setUpAutoComplete();
});

function setUpAutoComplete() {
    $.ajax({
        url: "ajax-getAllMeds.php",
        async: false,
        type: "GET",
        dataType: "text",
        success: function(result){
         var json = JSON.parse(result);
                if (!json || !json.meds) {
                    alert('invalid');
                }
                $("#med").autocomplete(json.meds);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
         alert(textStatus);
         return false;
        }
    });
}
ChaosPandion
+1  A: 

I was having the same problem with jquery autocomplete a couple of days ago to the point that I considered using the scriptaculous auto-complete, but it turned out to be a lot easier than I thought actually - kind of surprised at all the hair pulling I went through :)

As it turns out, this is all you need, seriously.. if you run into problems get back to me and I'll try to work it out with you.

Get your .php file ready. In my case, I called it "list.php" My table is called lists and has fields id and name. I'm retrieving the name only. These names are what's going to populate the selectable options.

Note that what the user types into the input box is passed as 'q'. This is the $_GET['q'] you see in line 2 of the code below. You can override/rename it if you want, but better to not bother. Note that it also has nothing to do with the name of the input field itself.

Note also that jquery autocomplete needs the "\n" to separate the results into independently selectable options. If you don't concatenate "\n", it will output all as a single selectable option.

//start with database connection of course
$rs = mysql_query("SELECT * FROM lists WHERE name LIKE '%" . $_GET['q'] . "%'");


while($row = mysql_fetch_assoc($rs)) {
    echo $row['name'] . "\n";
}

Get your input field ready. In my case, I called it name="myinputfield" but that's not important because the name doesn't matter, it's the id="searchterm" that matters

<input name="myinputfield" type="text" id="searchterm" size="30" maxlength="100" />

Then in your .js file, include the following:

$("#searchterm").autocomplete("list.php");

I did some extra stuff with the styling etc. because I wasn't happy with the default styling, but that's all you need to get the functionalirty going. The most important points are to use $_GET['q'] in your script and target the #searchterm id in your js.

Let me know if this solves your problem.

Chris
dude! that totally fixed the issue!! I had most of what you suggested except I was unnecessarily making it complicated by make it a JSON object. Thanks for your help!!
acedanger
Yeah, no need to set the ajax/json up. Plugin does all that for you in the background with the .autocomplete() I did the same thing initially too
Chris