Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of remote: true in rails

I followed a rails tutorial where we submitted a form with ajax. We used remote: true in form_for:

<%= form_for @task, remote: true do |f|   %>

Everything works fine. But I'm confused about remote: true. What is the purpose of remote: true?

like image 819
Haseeb Ahmad Avatar asked Nov 16 '25 04:11

Haseeb Ahmad


2 Answers

JS

remote: true is a part of the Rails UJS (unobtrusive Javascript) driver. It just adds the data-remote: true attribute to any object you add it to, allowing Rails's UJS script to bind it to some ajax functionality...

Some definition from Rails:

Note the data-remote="true". Now, the form will be submitted by Ajax rather than by the browser's normal submit mechanism.

You probably don't want to just sit there with a filled out , though. You probably want to do something upon a successful submission. To do that, bind to the ajax:success event. On failure, use ajax:error. Check it out:

It's pretty simple really....

enter image description here

It basically assigns a Javascript .on bind to any elements on your page which have data-remote: true. This is what sends the Ajax request for you.


Hooks

The important thing to note is that this method creates several "hooks" which you can use with your other javascript:

enter image description here

This allows you to use the remote: true functionality, and customise what happens by using the hooks above...

#app/views/messages/new.html.erb
<%= form_for @messages, remote: true do |f| %>
   <%= f.submit %>
<% end %>

#app/assets/javascripts/application.js
$(document).on("ajax:success", "#messages", function(event, data, status, xhr) {
    alert("Form submitted, thank you!");
});
like image 96
Richard Peck Avatar answered Nov 18 '25 19:11

Richard Peck


remote: true generates data-remote="true" as html

It submits form by ajax rather than browser's normal submit mechanism

Reference

like image 21
Prashant4224 Avatar answered Nov 18 '25 20:11

Prashant4224



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!