Jquery ajax populate dropdown with json response data
Asked Answered
B

2

1

I know there are quite a few questions floating on this but I'm still not sure what to do.

I have a HTML form called "CuisineForm", after the user selects the type of cuisine, the AJAX sends the form to the server. The AJAX call works fine, and server responds with a JSON responsewhich contains all the serving times of this particular cuisine. These serving times are divided into Breakfast, Lunch and Dinner.

These times need to be populated into 3 separate dropdowns in the same form. but I don't really know how to process the JSON results to populate the 3 dropdowns in the form.

Here is the JSON response from the PHP server side script. Note that this was generated in the PHP script using "echo json_encode()".

{"breakfast":[{"09:00:00":"9:00 am"},{"09:30:00":"9:30 am"}],"lunch":[{"12:00:00":"12:00 pm"},{"12:30:00":"12:30 pm"}],"dinner":[{"19:00:00":"7:00 pm"},{"19:30:00":"7:30 pm"}]}

Here is my $.post code.

$.post( "gettimeslots", $( "#CuisineForm" ).serialize(), function() {
          alert( "success" );
        })
          .done(function(data) {
            // Not sure what code to write here to populate dropdown

          })
          .fail(function() {
            alert( "There was a problem getting the dropdown values!" );
          })
          .always(function() {
            alert( "always" );
        });

Here is my dropdown that I want to populate

<select name="breakfasttimes" id="breakfasttimes"></select>
<select name="lunchtimes" id="lunchtimes"></select>
<select name="dinnertimes" id="dinnertimes"></select>

Most implementations tend to use $.getJSON. But as shown above I am using $.post instead. Please tell me if I should use $.getJSON instead.

Can someone offer some pointers or code advice?

Thanks Kevin

Bedwell answered 7/4, 2014 at 7:37 Comment(0)
M
2

Heres a fiddle that contains the full answer

HTML:

<select name="breakfast" id="breakfast"></select>
<select name="lunch" id="lunch"></select>
<select name="dinner" id="dinner"></select>

JS:

var data = {"breakfast":[{"09:00:00":"9:00 am"},{"09:30:00":"9:30 am"}],"lunch":        [{"12:00:00":"12:00 pm"},{"12:30:00":"12:30 pm"}],"dinner":[{"19:00:00":"7:00 pm"},{"19:30:00":"7:30 pm"}]};

// Put this code inside of the "done callback"
var $elements = $('#breakfast, #lunch, #dinner');
$.each(data, function (dataKey, dataVal) {
    $elements.each(function(domElKey, domElVal){
        if (dataKey === domElVal.id) {
            $.each(dataVal, function(timeKey,timeVal){
                $.each(timeVal,function(timePropKey, timePropVal){
                $(domElVal).append("<option>"+timePropVal+"</option>");
                });
            })
       }
    });
}); 

A fiddle that contains the answer

Montemayor answered 7/4, 2014 at 7:56 Comment(2)
Hi. This did put me on the right track. However I had to use run a parseddata = JSON.parse(data); before looping through it. If not I would get errors on some javascript errors on the first iteration of the main loop. I'm wondering why your example did not have to use JSON.parse?Bedwell
That depends on the response you get back from the server, it can return as a json, or a stringified json then have to be parsed, im not sure regarding what happens to the response after setting the dataType .Montemayor
S
0

You could use the $.each() function to loop through the data:

.done(function(data) {
$.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });

})

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

Refrence

Stetson answered 7/4, 2014 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.