How to pass data from jQuery to controller?

孤街醉人 提交于 2019-12-03 17:16:28

In my opinion, using AJAX and not reloading the page is a best bet here. You're simply trying to update some data, and there's no reason to perform a full page-refresh to do that. I'm not a RoR aficionado, but it would seem that we can send the data to the controller by doing ->

$.ajax({ 
  type: 'POST', 
  url: 'path/to/controller', 
  data: {'start_date' : $("input[name='report[start_date]']").val(), 
        'end_date' : $("input[name='report[end_date]']").val() }, 
  success: function(data){
    //data is whatever you RETURN from your controller. 
    //an array, string, object...something 
  } 
});`  

In your RoR controller, you'll get the params by doing...

var the_start = params[:start_date],
    the_end = params[:end_date]

Now you've got the data in your controller, you can apply the method to it. Then when you're ready to send the data back, return, print, whatever you do to send data to the page.

Also, RoR by default (when accessing a controller) expects to output a template to the view, since we just want to update data, you'll need to stop that default action using something like ->

render :layout => false

I hope this was helpful. I'm really not a RoR expert, but this is the method I used in the few times I dabbled.

Goodluck!

Rails 3 now has helpers to do exactly what you want. These are known as remote forms and links.

This blog post does a great job of explaining what they do and how they work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!