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/........"
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;
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.