JavaScript

caven xu
PRO
caven xu
Pro Student 12,504 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?

Update:

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
8,905 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.

$(document).ready(function(){
    $('form').submit(function(evt){
        evt.preventDefault();
        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= "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
        var flickrOptions= {
            tags: animal,
            format: "json"
        };
        function displayPhotos(data){
            //check to see if there is data returned
            if($.isEmptyObject(data.items)=== false){
                $('#photos').html();        
                var photoHTML= "<ul>";
                $.each(data.items, function(i, photo){
                    photoHTML+= '<li class="grid-25 tablet-grid-50">';
                    photoHTML+= '<a href="' +photo.link+ '" class="image">';
                    photoHTML+= '<img src="' +photo.media.m+ '"></a></li>';
                });
                photoHTML+= "</ul>"
                $('#photos').html(photoHTML);

                //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
caven xu
caven xu
Pro Student 12,504 Points

Thanks for you to following my question. Since I don't have enough experience to handle complex ajax. I found a alternative solution — datatables — to help me. That's a handy tool for solving this kind of scenarios.