Skip to content

Ajax CRUD

JP Barbosa edited this page Jul 23, 2015 · 2 revisions

Ajax CRUD

Add event listeners to elements with data-remote and "btn" CSS class
nano app/assets/javascripts/application.js
...
// Add Ajax CRUD
var ready;
ready = function() {
  var container, modal;
  modal = $("#modal");
  container = $("#container");
  container.on("ajax:success", ".btn[data-remote=true]", function(e, data, status, xhr) {
    modal.find(".modal-body").html(xhr.responseText);
    modal.modal('show');
  }).on("ajax:error", function(e, xhr, status, error) {
    container.append("<p>ERROR</p>");
  });
  modal.on("ajax:success", "form", function(e, data, status, xhr) {
    if (xhr.responseText.indexOf('was successfully created') !== -1) {
      container.html(xhr.responseText);
      modal.modal('hide');
    } else {
      modal.find(".modal-body").html(xhr.responseText);
    }
  }).on("ajax:error", function(e, xhr, status, error) {
    modal.append("<p>ERROR</p>");
  });
}
$(document).ready(ready);
$(document).on('page:load', ready);
Change application controller to not render layout for XHR requests
nano app/controllers/application_controller.rb
  ...
  skip_before_action :verify_authenticity_token, if: :json_request?
  layout proc { false if request.xhr? }
  ...
Change articles controller save to redirect to index after success
nano app/controllers/articles_controller.rb
...
      if @article.save
        format.html { redirect_to articles_url, notice: 'Article was successfully created.' }
...
Add id to container DIV and basic Bootstrap modal in the layout
nano app/views/layouts/application.html.erb
...
<div id="container" class="container">
  <%= yield %>
</div>
<div class="modal" id="modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body"></div>
    </div>
  </div>
</div>
...
Add data-remote to create articles button and in the articles form
nano app/views/articles/index.html.erb
<%= link_to 'New Article Using Ajax', new_article_path, class: 'btn btn-primary', remote: true %>
nano app/views/articles/_form.html.erb
<%= simple_form_for(@article, remote: request.xhr?) do |f| %>
Open articles in the browser and create a new article to validate
open http://localhost:3000/articles
Add Ajax CRUD to Git
git add .
git commit -m "Add ajax CRUD to insert articles"
Next step: Send Email