caven xu
caven xu
5,047 Points

When I get data(array) from ajax response, how could I pass it to a partial which will generate a table?

I just finished "AJAX Basics" course. I try to use ajax "keyup" event to make a dynamic search form in my rails app. But I don't know how to pass the returned data to the partial. I asked this on stackoverflow but don't get answer so far. here's the question details. Can anyone give me some tips?


I tried use a $.each() loop, here is my code. But the code is ugly and I don't know how to add links(like add_to_cart) in it.

1 Answer

Nikola Jankovic
Nikola Jankovic
5,317 Points

Hello, I just finished same course. The solution in the final video with submit, not keyup, already generate live search. There is no need for changing anything. Here is my js code, inside it there is also a solution for message when we don't get any result.

        var $searchField= $('#search');

        //Whit this we upgrade search button
        var $submitButton= $('#submit');
        $searchField.prop('disabled', true);
        $submitButton.attr('disabled', true).val('Searching...');

        var animal= $searchField.val();
        var flickerAPI= "";
        var flickrOptions= {
            tags: animal,
            format: "json"
        function displayPhotos(data){
            //check to see if there is data returned
            if($.isEmptyObject(data.items)=== false){
                var photoHTML= "<ul>";
                $.each(data.items, function(i, photo){
                    photoHTML+= '<li class="grid-25 tablet-grid-50">';
                    photoHTML+= '<a href="' '" class="image">';
                    photoHTML+= '<img src="' '"></a></li>';
                photoHTML+= "</ul>"

                //With this code we return search instead searching...
                $searchField.prop('disabled', false);
                $submitButton.attr('disabled', false).val('search');
            }else {
                $('#photos').html('<h1> There is no results for '+animal+ ' .</h1>');
                $searchField.prop('disabled', false);
                $submitButton.attr('disabled', false).val('search');

        $.getJSON(flickerAPI, flickrOptions, displayPhotos);
    }); //end submit
}); //end ready