0

I have a website which contains photos and videos and 3 buttons. One show only photos, one only videos and the last one show photos & videos. I have two different tables in the database (photos, videos) which contains only the name of the file. Their is no relationship between them.
Here is a example of my AJAX used to only show videos :

jQuery(document).ready(function() {
    $('#btn-videos').on('click', function(e){
    e.preventDefault();
    $.ajax({
    type:'GET',
    url:'/galerie',
    dataType: 'json',
    data: { 'type' : "videos", }
    });
    });
});

Here is my galerie controller :

  def index
     case params[:type]
     when "videos"  
        @medias = Video.order('created_at DESC')
     when "images" 
        @medias = Picture.order('created_at DESC')
     else 
        @medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)
     end
  end

My AJAX is calling the controller but it doesn't update the view.
Is their a (better) way to do this ?
I'm also wondering if its possible to do this line using only sql :

@medias = (Video.order('created_at DESC') + Picture.order('created_at DESC')).sort_by { |model| model.created_at }.in_groups_of(3)
1
  • Instead of ajax in js file I will say call with remote and handle it via index.js.erb Commented Mar 30, 2017 at 14:04

1 Answer 1

1

You can do this in two ways:

  1. send a remote request through your button and handle data update on index.js.erb file (in views folder). You can refer to this link.
  2. Use ajax in js file in your asset. Once the ajax request is successful you need to replace your old data with your requested new data.

    $('#btn-videos').on 'click', ->
       e.preventDefault();
       $.ajax
         type:'GET',
         url:'/galerie',
         dataType: 'json',
         data: { 'type' : "videos", }
         success: (data) ->
           console.log(data)
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.