-
Notifications
You must be signed in to change notification settings - Fork 8
Ajax CRUD
JP Barbosa edited this page Jul 23, 2015
·
2 revisions
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);
nano app/controllers/application_controller.rb
...
skip_before_action :verify_authenticity_token, if: :json_request?
layout proc { false if request.xhr? }
...
nano app/controllers/articles_controller.rb
...
if @article.save
format.html { redirect_to articles_url, notice: 'Article was successfully created.' }
...
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>
...
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 http://localhost:3000/articles
git add .
git commit -m "Add ajax CRUD to insert articles"