Skip to content

Instantly share code, notes, and snippets.

@hungmi
Last active December 18, 2019 08:08
Show Gist options
  • Save hungmi/cb057b51b3d79f524a8533d89f37bd97 to your computer and use it in GitHub Desktop.
Save hungmi/cb057b51b3d79f524a8533d89f37bd97 to your computer and use it in GitHub Desktop.
Rails 4 with jquery-ujs: event listeners for remote link js success and error events
//// For Rails projects with rails-ujs Check official guide: https://guides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers
// In xxx.html.erb, we can write
// <%= link_to 'xxx', url, remote: true, data: { type: :json, disalbe_with: "...", confirm: "ok?" }, class: 'js-remote-link' %>
$(document).on("ajax:success", ".js-remote-link", function(e) {
var data = event.detail[0]
var status = event.detail[1]
var xhr = event.detail[2]
console.log(data) // {message: "SUCCESS &check;"}
console.log(status) // OK
console.log(xhr)
console.log(data.message) // "SUCCESS &check;"
})
// In xxxxx_controller.rb, we can write
// format.json { render json: { message: "SUCCESS &check;" }, status: '200' }
$(document).on("ajax:error", ".js-remote-link", function(e) {
var data = event.detail[0]
var status = event.detail[1]
var xhr = event.detail[2]
console.log(data) // {message: "FAILED &cross;"}
console.log(status) // Internal Server Error
console.log(xhr)
console.log(data.message) // "FAILED &cross;"
})
// In xxxxx_controller.rb, we can write
// format.json { render json: { message: "FAILED &cross;" }, status: '500' }
------------------------------
//// For older Rails projects with jquery-ujs https://github.com/rails/jquery-ujs
//// All events https://github.com/rails/jquery-ujs/wiki/ajax
$(document).on("ajax:success", ".js-remote-link", function(e, data, status, xhr) {
console.log(data.message) // "SUCCESS &check;"
})
// In xxxxx_controller.rb, we can write
// format.js { render json: { message: "SUCCESS &check;" }, status: '200' }
$(document).on("ajax:error", ".js-remote-link", function(e, xhr, status, error) {
console.log(xhr.responseJSON.message) // "FAILED"
console.log(status) // "error"
console.log(error) // "Internal Server Error"
})
// In xxxxx_controller.rb, we can write
// format.js { render json: { message: "FAILED" }, status: '500' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment