January 23, 2014

Sending POST data with links (AJAX)

Handling AJAX requests in Rails is pretty easy thanks to the jquery-ujs library. This library is enabled by default in every new Rails application. You can do standard, but also some pretty crazy things with it with ease.

For example you can send POST data with AJAX after click on the HTML link element generated with link_to helper.

# some view
<%= link_to 'AJAX action with POST request',
            ajax_path, 
            data: {
              remote: true,
              method: :post,
              params: { param1: "Hello server" }
            } %>

Above code will generate following HTML (but with escaped quotes in data-params).

<a data-method="post" data-params="{"param1":"Hello server"}" data-remote="true" href="/ajax">AJAX action with POST request</a>

After click on this link new AJAX request will be send to the server. This POST request will contain parameter param1 with value Hello server. There is no additional configuration needed thanks to the above mentioned jquery-ujs.

But you can also set POST data dynamically after the click. For example you want to send IDs of all selected elements.

$ ->
  $('a').bind 'ajax:beforeSend', (event, xhr, settings) ->
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    settings.data = $.param { ids: someFunctionToGetIds() }

Setting request header to application/x-www-form-urlencoded is needed just for links. If you use button_to, then is is already set. Personally I would rather use button_to for sending POST data, but sometimes it is easier to use just a link.

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.