9

I am a complete noob with JSON parsing in jQuery. Thought I got the response... My data is in this form:

Array(
[1]=>abc,
[3]=>mango,
[4]=>apple,
[5]=>fruits
)

In this way I want this list to appear as an autocomplete list. I am using.

    jQuery("#name").autocomplete( '<?php echo HTTP_PATH.'/songs/sss'; ?>', {
    multiple: true,
    mustMatch: true,        
    matchContains: true,
    autoFill: false,
    dataType: "json",
    parse: function(data) {
            return jQuery.map(data, function(item) {
                return { data: item, value: item.label, result: item.label};
            });
        },
        formatItem: function(item) {
            return item.label;
        },
        formatResult: function(item) {
            return item.id;
        },
        formatMatch: function(item) {
            return item.label;
        }

});

I want the value when it shows list, i.e. the label from my data. When I select a label then it should show the label. But at the time of submission it should actually submit the key. I mean I want it to work as select box of HTML.

Returned JSON

 [{"id":1,"label":"Mehdi Hassan"},{"id":2,"label":"Jagjit Singh"},{"id":3,"label":"Suresh Vadekar"}]
dda
  • 6,030
  • 2
  • 25
  • 34
Rahul Singh
  • 1,614
  • 6
  • 22
  • 39

5 Answers5

11

Your JSON seems to not be an array, just an object (hash map). Check out official docs:

Expected data format

The data from local data, a url or a callback can come in two variants:

  • An Array of Strings: [ "Choice1", "Choice2" ]

  • An Array of Objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

In your case it should be in the following format:

[
   {"1":"Shad.aab"},
   {"158":"Adadad"},
   {"159":"Asdadad"},
   {"166":"Abbas"},
   {"167":"Sdadad"},
   {"171":"Shadaab Please check it out"},
   {"173":"Check This Please"},
]

(Remember that left side is label, right value, I suppose in your data, all should be reversed...)

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
5

If I understand you correctly, you want to use autocomplete to populate a name textfield, but want to leverage another value associated w/ the name in the form POST.

[If you're able to use latest jQueryUI version of autocomplete] - Following the "Custom Data and Display" autocomplete example at http://jqueryui.com/demos/autocomplete/#custom-data, you'll see that on autocomplete hint, they display the selected label, however, they also save an associated value in a hidden input that is also posted back to server. Given your current json format:

html:

<label for="username">Name:</label>
<input id="username" size="50" />             <!-- holds display name -->
<input id="userid" name="userid" size="50" /> <!-- holds userid -->
...

js:

<script>
  $("#username").autocomplete({
    source: '<?php echo HTTP_PATH.'/songs/sss'; ?>',

    // Update display name when user mouses over selection
    focus: function( event, ui ) {
      $( "#username" ).val( ui.item.label );
      return false;
    },

    // Set display name and hidden input on user selection
    select: function( event, ui ) {
      $( "#username" ).val( ui.item.label );
      $( "#userid" ).val( ui.item.id );
      return false;
    }
  }); 
</script>

php POST target:

<?php
  // Use [hidden] input to do your magic
  if(isset($_POST['userid']))
    echo 'Wooo..here is my key: ' . $_POST['userid'];
?>
ltiong_sh
  • 3,186
  • 25
  • 28
3

The problem looks like it's here:

jQuery("#name").autocomplete( '<?php echo HTTP_PATH.'/songs/sss'; ?>', { multiple: true, ...

It should be like this:

jQuery("#name").autocomplete( { source: '<?php echo HTTP_PATH.'/songs/sss'; ?>', multiple: true, ...

Also make sure you are using it on load/ready and not just inside a plain <script> tag

$(function(){ jQuery("#name").autocomplete(); });

Use firebug to verify that when you type a letter in that field it sends a request to the source page set for autocomplete.



Here is the code I used to re-create/fix your problem:

index.php

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.20.custom.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
    $(function(){
        jQuery("#name").autocomplete({
            source: 'index_json.php',
            multiple: true,
            mustMatch: true,
            matchContains: true,
            autoFill: false,
            dataType: "json",
            parse: function(data) {
                return jQuery.map(data, function(item) {
                    return { data: item, value: item.label, result: item.label};
                });
            },
            formatItem: function(item) {
                return item.label;
            },
            formatResult: function(item) {
                return item.id;
            },
            formatMatch: function(item) {
                return item.label;
            }
        });
    });
</script>
</head>
<body>
    <form>
        <label for="name">Name: </label>
        <input id="name" name="name" />
    </form>
</body>
</html>

index_json.php

<?
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo '[{"id":1,"label":"Mehdi Hassan"},{"id":2,"label":"Jagjit Singh"},{"id":3,"label":"Suresh Vadekar"}]';
?>




I am very confused with your request, but have taken your code and made it work how you specified (I think).

I want value when it show list.i.e. Label from my data. When I select label than also it should show label. but at time of submission it should actually submit key. I mean i want it to work as select box of HTML.

It almost sounds as if you want an input box for just searching and a static select list that changes from autocomplete but stays there instead of disappearing...

Brandon
  • 51
  • 7
  • I still has not find right solution. I meant when I click on textbox I suggested four names by script(thing is going well. Even I am getting.) But in case if I select any of the name then respective id should get selected (Its similar to select box). That we have list of names but as if we select any of that than its value is return on form submission. – Rahul Singh May 24 '12 at 02:19
  • I just need to parse it better way – Rahul Singh May 24 '12 at 02:29
3

You need to do json_encode($your_array) in backend.

It will convert PHP Array into your JSON encoded strings that your front-end (jQuery) can then parse and process.

Daniele B
  • 3,117
  • 2
  • 23
  • 46
  • if you want to answer properly and be upvoted please answer more extenisvely giving some code if possible – Daniele B May 28 '12 at 23:32
1

I am not sure I understood your question well. But I faced the same kind of requirement in my experience. I used ajax autocomplete js from the above link. (Go thru the link for complete details)

The highlight here is, this js provides you a callback onSelect with which you can set your values after selection of the auto complete suggestion.

The json encoded string should be like

query:'Li',
suggestions:['Mahendi Hassan','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['1','2','3','4']
  • query - original query value
  • suggestions - comma separated array of suggested values
  • data (optional) - data array, that contains values for callback function when data is selected.

Now have some hidden input field in your form, and set the selected suggestion's data to value of that hidden input field like this.

jQuery(function () {
    options = {
        minChars: 2,
        serviceUrl: "ur/php file",
        onSelect: function (value, data) {
            $('#hiddenUserProfileIdProps').val(data);  //Setting value to hidden field
        }
    });
    a = $('#enterEmailLink').autocomplete(options);
    a.disable();
});

Then submit your form. Thats it.

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
Jebin
  • 702
  • 13
  • 33