Skip to content Skip to sidebar Skip to footer

How Do I Pass Params To Rails Controller Method Then Return Value Using Jquery/ajax?

I am using a click function to first get the array/position, then post it via an AJAX call to a controller method. I would then like the method to return a boolean value to enable

Solution 1:

url: "https://localhost:3000/chess/:pos", won't be interpolated, unless I'm completely missing something.

With post '/chess/:pos' => 'chess#select' you're telling the Rails (its router specifically) to look for a param inside the request path in the position of :pos, and when it finds it, set the value of the params hash (at params[:pos]) to the string at :pos in the path.

jQuery doesn't know anything about Rails' router. Neither does Javascript.

To see what I mean, add this to your routes.rb file:

get '/:cookies/and/:cream' => 'application#test'

in application_controller.rb, add the following:

deftest
  render :text => "I love me some #{params[:cookies]} with my #{params[:cream]}"end

then hit http://localhost:3000/chocolate-chip/and/milk

should read "I love me some chocolate-chip with my milk"

Now, assuming your other code is fine,

$("#backboard").on("click", "div", function(e){
       $("#backboard div").removeClass("selected");
       var val = $(this).data('val');
     $.ajax ({
        type: 'POST',
        url: "http://localhost:3000/chess/" + val,
        success: function(d){
          if(d === true){
            $(this).addClass("selected").append("<p>"+val+"<p>");
          }
        }
      });

should do it. No need to pass any additional data in the ajax function.

Also, don't use HTTPS in development. It'll just cause you headaches.

Post a Comment for "How Do I Pass Params To Rails Controller Method Then Return Value Using Jquery/ajax?"