views:

63

answers:

3

I have tried so many things but I don't understand this sooo confusing.

I have this

<input id="wba" type="search" name="q" value="" class="search box" />
<input type="submit" value="Go" class="search button" />

also a php file

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

$arr = array('test'=>'hello world');

echo json_encode($arr);

as for javascript I have tried everything including the demos from the jquery website but no luck ... someone out there help me setup the autocomplete to display the data?

EDIT

$(function() {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").attr("scrollTop", 0);
        }

        $("#wba").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "search.php",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function(data) {
                        response($.map(data.sites, function(item) {
                            alert(item);
                            window.console.debug(item);
                            return {

                                label: item.name ,
                                value: item.url
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                log(ui.item ? ("Selected: " + ui.item.name) : "Nothing selected, input was " + this.value);
            },
            open: function() {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function() {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    });

This code is from the jqueryui website (demo) ...

A: 

The basic premise, without any code, is this:

  • In jQuery, bind an event listener to the input so that when the user types something, a function is called
  • That function then sends the value of the input to your php script using one of jQuery's ajax functions
  • The php script echos a json encoded string
  • The jquery ajax function receives the string
  • That function then takes the json data and appends it in some stylized way to the outside of the input
  • Each of those options has an event listener bound so that when an option is clicked, something happens - either the input is filled with the clicked item, another function is run, a page is loaded, etc.

There are a lot of different ways to accomplish this, which is why I didn't answer with an actual function. It depends on your goals.

hookedonwinter
I think the poster is asking how to feed JSON into the [jQuery UI autocomplete widget](http://jqueryui.com/demos/autocomplete/) :)
Nick Craver
I didn't ask for the process I am familiar with that... i just can't get the returned data to go to the drop down or log or however ppl like to call it :)
Val
@Nick ah. Missed that :) @Val My bad on the assumption.
hookedonwinter
yes @nick :) thats what i meant
Val
A: 

Here is how I implemented it using C# on the server.

JavaScript

function InitializeElement (element) {
    element.autocomplete("ServerPage.ashx", {
        formatItem: function(data) {
            return "<span style=\"font-size:9pt;word-break:break-all;\">" + data[0] + "<br />" + data[1] + "</span>";
        }
    });
    element.result(function(event, data, formatted) {
        jq(event.currentTarget).siblings('input[type=hidden]').val(data[2]);
        event.currentTarget.value = data[0];
        event.currentTarget.title = data[1];
    });
}

C#

public class ServerPage : ApplicationHandler 
{ 
    protected override void Process()
    {
        String text = (this.Request.Params["q"] ?? String.Empty);

        if (text.Length > 0)
        {
            using (DatabaseRecords records = this.Core.Database.ExecuteRecords("StoredProcedure", new KeyValue("Text", text)))
            {
                while (records.Read())
                {
                    Response.Write(records.GetString("Code") + "|" + records.GetString("Description") + "|" + records.GetInt32("Id") + "\n");   
                }   
            }
        }       
    }
}
ChaosPandion
+1  A: 

It should be something like this

// JS
$(function() {
  $("#wba").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "search.php",
        dataType: "jsonp",
        data: { q: request.term },
        success: function(data) {
          response($.map(data, function(value,key) {
            return { label:value.label , value: value.val }
          }));
        }
      });
    },
    minLength: 2
  });
});​

// PHP
$results = array(
   array('label' =>'label1', 'val' => 'value1'),
   array('label' =>'label2', 'val' => 'value2'),
   array('label' =>'label3', 'val' => 'value3')
);
// Optionally do something with the user input ($_GET["input_value"])
echo $_GET['callback'].'('.json_encode($result).');'​​​​​​​​​

i dont know why but this does work...

it doesn't work... it returns the jason data but there is nothing dropping down
Val
do you have an url?
http://jsfiddle.net/xYdPt/ just copied and pasted the html file on it
Val
updated code, i can give you the example link if you want but it should work... fingers crossed
thnx man the only problem there is that it expects at lest two characters before it fires
Val
until u remembered the minLength
Val