0

In the question asked here, i see that the following code can be used for adding options to SELECT

function getResults(str) {
  $.ajax({
        url:'suggest.html',
        type:'POST',
        data: 'q=' + str,
        dataType: 'json',
        success: function( json ) {
           $.each(json, function(i, optionHtml){
              $('#myselect').append(optionHtml);
           });
        }
    });
};

Can someone please tell me, what the format of the json should be, on the php server side. Like, how should it be created, so that it is parsed correctly by "$('#myselect').append(optionHtml);" ??

Community
  • 1
  • 1
Archer
  • 1,152
  • 4
  • 12
  • 34
  • Note: to insert a block of code into a question or answer, select it and press the `{}` button, or indent it four spaces. (Don't quote it with ` - that's for `inline code`.) – nnnnnn Feb 10 '13 at 07:03
  • ohh.. okk .. thanks .. i m new here .. still learning .. looks like a great site though .. – Archer Feb 10 '13 at 07:04

3 Answers3

4

That code would parse this JSON, basically an array of strings with markup.

[
    "<option value='...</option>",
    "<option value='...</option>",
    "<option value='...</option>",
    ...
]

This pretty much defeats the purpose of JSON though.


It would have been better if the JSON contained only the data:

{
    "text1" : "value1",
    "text2" : "value2",
    "text3" : "value3",
    ...
}

and your code to parse it and create the elements for you. That way, the JSON is lighter.

success: function( json ) {
    var mySelect = $('#myselect')
    $.each(json, function(key,val){
        $('<option/>',{
            value : val //i like this method of making elements better
        })              //because string concatenation is messy
        .text(key)
        .appendTo(mySelect);
    });
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Thank you very much for the suggestion!!! .. i have changed my code according to it. But again, there is a small issue. All the names in the SELECT seems to populating as one character each .... i.e. one character per option. What am i doing wrong? – Archer Feb 10 '13 at 07:27
  • @Archer can you post a demo or screenshot of this issue. – Joseph Feb 10 '13 at 07:31
  • I think a better idea would be to just pass the option values in the request, and in the callback construct the entire string like `"option value = '"+value+"'>"`. That way, the amount of data received through the Ajax call is reduced... – SexyBeast Feb 10 '13 at 07:34
  • @JosephtheDreamer i have uploaded the image here http://i.stack.imgur.com/6Wh9J.jpg ... see, the options are with one character each, with the json syntax characters also. – Archer Feb 10 '13 at 07:39
  • @JosephtheDreamer, and my server side php is this `{$req = 'SELECT DISTINCT state_name FROM s1_cities'; $query = mysql_query($req); $results[] = 'Select State'; while($row = mysql_fetch_array($query)) { $results[] = $row['state_name']; } return json_encode($results);}` – Archer Feb 10 '13 at 07:43
  • @Archer seems like the JSON was not parsed properly and instead you were given a string. check if you set `json` as the ajax data type. if all else fails, you can manually decode json using `JSON.parse(json_string)` – Joseph Feb 10 '13 at 07:45
  • @nnnnnn, Sorry, didn't notice that..:D – SexyBeast Feb 10 '13 at 07:45
  • @JosephtheDreamer, Thank you very very much for your help. Yes, i had missed the datatype field in the ajax, i have added it now. Thanks for the suggestion again . Works Great. !!! – Archer Feb 10 '13 at 07:48
0

To use with the JS you've shown you'd need the JSON to be an array like this:

["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]

...where each array element is the appropriate html for a single <option> element.

(That is, exactly like the first JSON shown in that other question.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

JSON is a collection of key value/name pairs. These can be in the form of Objects or Arrays or both.

Let me assume that you want to have two dropdowns and First dropdown has Countries and the second one has the cities of that particular country in it. In this case the JSON structure would be like the below:

{
  "<select value='usa'>USA</select>": "<option value='boston'>Boston</option>",
  "<select>FRANCE</select>": "<option value=paris'>Paris</option>",
  "<select>UNITED KINGDOM</select>": "<option value=london'>London<option value=not'>Nottingham</option>",
  "<select>GERMANY</select>": "<option value='munich'>Munich</option>"
}

JSON Validated at http://jsonlint.com/

defau1t
  • 10,593
  • 2
  • 35
  • 47
  • This isn't right. You need to append HTML option elements to the select in order for them to work correctly. – Eric Freese Feb 10 '13 at 07:16
  • @EricFreese: I am just talking about the JSON structure, you could always later in your html add something like this $('body').append($(' – defau1t Feb 10 '13 at 07:18
  • I didn't downvote, but the question explicitly asks for a JSON structure that will work with the existing JavaScript shown above - so the JSON would need to contain html markup for each option. – nnnnnn Feb 10 '13 at 07:22