3

I am trying to make ajax post request in rails application. But i am getting error in response.

Rails code:-

def search_exams(myparam1 , myparam2)
   json_data = {:aaData=> [["abc","xyz","lmnop"],["sdf","adsdf","sadfsd"],["sdf","adsdf","sadfsd"]]}.to_json
   respond_to do |format|
     format.json { render :json => json_data }
   end
end

Script Code:-

<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>


<script>
$.ajax({
        url:'/home/search_exams',
        type:'POST',
        dataType:'json',
        data:{
            myparam1: "First Param value",
            myparam2: "Second param value",
            authenticity_token: window._token
        },
        success:function(data){
            debugger;
        },
        error:function(data){
            debugger;
        }
    });
  </script>

I am getting this error:-

"ArgumentError in HomeController#search_exams wrong number of arguments (0 for 2) Rails.root: C:/Users/........"

1 Answer 1

7
def search_exams

Remove arguments from the method.

When you pass a request with params to a Rails controller, the middleware stack puts them into the params hash, so you'll get:

params[:param1]
params[:params2]

--

You'll also want to consider making your JS unobtrusive:

#app/assets/javascripts/application.js
$(document).on("action", ".element", function(){
     $.ajax({
        url:'/home/search_exams',
        type:'POST',
        dataType:'json',
        data:{
            myparam1: "First Param value",
            myparam2: "Second param value",
            authenticity_token: window._token
        },
        success:function(data){
            debugger;
        },
        error:function(data){
            debugger;
        }
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

ohh.. Thank you Rich Peck.
Updating answer for you

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.