LearningROR LearningROR - 9 months ago 34
Ajax Question

ajax:success not triggering ajax rails 4 app

I have jQuery function in rails application from which I am trying to make ajax calls.

The problem is its not returning ajax response but its sending ajax calls successfully.

I need to bind my ajax call with that function so I may be able to show response.

jQuery code:

$(document).ready(function () {
$("#contact_us").bind("ajax:success", function (e, data, status, xhr) {
if (data.success) {
} else {

Rails Code:

class MailController < ApplicationController
prepend_before_action :check_captcha

def contact_us
full_name = params['contact_full_name']
last_name = params['contact_last_name']
phone = params['contact_phone']
website = params['contact_website']
email = params['contact_email']
message = params['contact_message']
ContactMailer.send_email(full_name, last_name, phone, website, email, message)

def check_captcha
unless verify_recaptcha
return render json: {:success => false, :message => "You cant use this captcha code"}
return render json: {:success => true, :message => "Your email has been sent successfully"}

Rails Form:

<%=form_tag contact_us_mail_index_path, :id => "contact_us",
:format => :json, :remote => true do %>


Button Code:

<button type="submit" class="btn btn-lg btn-default"><i class="fa
fa-check"></i> SEND MESSAGE</button>


//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require plugins/jquery/jquery-2.2.3.min.js
//= require scripts
//= require plugins/slider.revolution/js/jquery.themepunch.tools.min
//= require plugins/slider.revolution/js/jquery.themepunch.revolution.min
//= require view/demo.revolution_slider
//= require plugins/smoothscroll
//= require contact


resources :mail, except: [:show,:new,:create,:edit,:update,:destroy] do
collection do
post :contact_us


After number of attempts I finally resolved the problem.

The problem is related to turbolinks. Based on my research the problem was in application.js file.

I made number of changes and found turbolinks js is creating problem.

So, I installed a gem named: jquery-turbolinks

After installation, my application.js is like:

//= require plugins/jquery/jquery-2.2.3.min
//= require jquery.turbolinks
//= require jquery_ujs
//= require scripts
//= require contact

The answer posted my @SpunkyLive answer really helped me a lot but it was not enough to give me direction and fix for the code as well.