0

My problem involves passing values from JS to controller and then using them to query and return some output data. These values are as a result of selections in the UI:

<!-- Select car make -->
<ul id = "make">
   <% Car.all.each do |c| %>
      <li><%= link_to c.make, todos_data_path(:make_id => c.id), :method => :post, remote: true %></li>
   <% end %></ul>

<!-- Select car body -->
<ul id = "body">
   <% Type.all.each do |t| %>
       <li><%= link_to t.name, todos_data_path(:body_id => t.id), :method => :post, remote: true %></li>
   <% end %></ul>

Extract the selected values in JS:

var make = $('#make').text();    
var body = $('#body').text();  

After searching I learnt from a post that one cannot pass variables from JS to Rails directly. Instead, pass values to the controller by appending them as params in url. From my understanding what I need can be done in three basic steps:

Step 1: Create query string parameters using JavaScript. One way way to do this:

var url = "http://www.myapp/todos/data?" + $.param({make_id: make, body_id: body})
//http://www.myapp/todos/data?make_id=4&body_id=3

Step 2: Append the query string to the url. Following an earlier question one can append the query string to url by:

window.open(url, "_self");

Step 3: Run the url string and use params in the controller.

My routes:

resources : todos, only: [:index, :new, :create , :destroy]
get '/todos/data (:make_id)(:body_id)' => 'todos#data'

Controller:

def data
    @make = params[:make_id]
    @body = params[:body_id]

    @vehicles = Vehicle.where(make: @make, body: @body )

    respond_to do |format|
      format.html{ redirect_to root_path }
      format.js { }
    end
end

The output after running the string in the url:

Started GET "/todos/data?make_id=2&body_id=3" for 10.240.0.185 at 2017-05-24 12:55:58 +0000
Processing by TodosController#data as HTML
Parameters: {"make_id"=>"2", "body_id"=>"3"}
Redirected to http://myapp/
Completed 302 Found in 4ms (ActiveRecord: 0.6ms)

It seems that everything works fine up to the point where there is redirect_to root_path. I would like instead format.js { } executed since my aim is to render data.js.erb. How can I make the action respond to JS format instead of HTML? I tried specifying in the route get '/todos/data(:make_id)(:body_id)' => 'todos#data', :defaults => { :format => 'js { }' } but it generated unknown format error .

I have posted the whole process of what I am trying to do for clarity on what I want to achieve and maybe get suggestions on how to do the whole thing differently.

EDIT: I need also to show my todo.js

$( document ).on('turbolinks:load', function() {
    $('#make').on('click', 'li', function (event){
        event.preventDefault();
        $('.active').removeClass('active');
        var text = $(this).text();
        $(this).addClass('active');
    });

    $('#body').on('click', 'li', function (event){
        event.preventDefault();
        $('.active').removeClass('active');
        var text = $(this).text();
        $(this).addClass('active');
    });
});

1 Answer 1

0

When you are executing window.open(url, "_self");, it is requesting as a html get request. Why don't you use ajax?

 $.ajax({
   url: url,
   method: "GET",
   dataType: "script", /*optional*/
   success: function(response){
    console.log(response)
   }
 })

Option 2:

$("a").on("click", function(){
   $.ajax({
      url: "http://www.myapp/todos/data",
      type: "get",
      dataType: "script",
      data: { 
        make_id: make, 
        body_id: body 
      },
      success: function(response) {
        console.log(response);
      },
      error: function(xhr) {
        //Do Something to handle error
      }
  });
  return false;
})

in the place of $("a"), use your desired selector.

Sign up to request clarification or add additional context in comments.

12 Comments

I suspect the ajax does not run since nothing is logged to console. I even added alert(response) but no pop-up comes.
Did you mention dataType as js?
Yes, I did. This I put in the data.js.erb
I have edited my answer. That should work. Make sure the the link_to doesn't send the request to the server. Ajax should handle the request.
Sorry, I copied the output I was getting before. The output using the ajax after I hit one of the UI links to send a request is: Started POST "/todos/data?make_id=2" for 10.240.1.45 Processing by TodosController#data as JS Parameters: {"make_id"=>"2"} Rendering todos/data.js.erb Vehicle Load (0.6ms) SELECT "vehicles".* FROM "vehicles" WHERE "vehicles"."make" = $1 AND "vehicles"."body" = $2 [["make", "Saab"], ["body", "wagon"]] Rendered todos/_graph.html.erb Rendered todos/data.js.erb Completed 200 OK in 10ms (Views: 5.3ms | ActiveRecord: 1.3ms)
|

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.