0

I have an AJAX form that I'm looking to submit the data via AJAX to a function for a controller in the background. Right now, I have the JS below and am using the controller code below to test. However, while the function returns a 200 response and I can see the response in Firebug the success and error functions are not running. Any ideas?

$('contact_form').submit(function() {  
    var valuesToSubmit = $(this).serialize();

    $.ajax({
        url: $(this).attr('action'),
        data: valuesToSubmit,
        dataType: 'json',
        type: 'POST',
        success: function(data) {
            alert('success');
        },
        error: function(data) {
            alert('error');
        }
    });

    return false; // prevents normal behavior
});

I've tried code beyond alerts and it still doesn't work. Also, here's the controller below. Help is greatly appreciated

def ajax_response
    render :json => { 
        :name => 'test'
    }     
end

*Edit - Adding HTML form in case that's relevant here

<form accept-charset="UTF-8" action="/contact_message" data-remote="true" id="contact_form" method="post">

<label for="name">Name</label><span class="color-red">*</span>
<div class="row margin-bottom-20">
    <div class="col-md-7 col-md-offset-0">
        <input class="form-control" id="name" name="name" type="text" />
    </div>
</div>

<label for="email">Email</label><span class="color-red">*</span>
<div class="row margin-bottom-20">
    <div class="col-md-7 col-md-offset-0">
        <input class="form-control" id="email" name="email" type="text" />
    </div>
</div>

<label for="message">Message</label><span class="color-red">*</span>
<div class="row margin-bottom-20">
    <div class="col-md-11 col-md-offset-0">
        <textarea class="form-control" id="message" name="message" rows="8"></textarea>
    </div>
</div>

<p>
    <button class="btn-u" name="button" type="submit">Send Message</button>
</p>

</form>
Splashlin
  • 7,225
  • 12
  • 46
  • 50
  • can you add a complete/always handler and see whether it is getting called... either the success or the error handler has to get called... – Arun P Johny Oct 07 '14 at 03:47
  • Hmm, always/done handlers not working either – Splashlin Oct 07 '14 at 04:14
  • 1
    Do some elementary debugging. Put a `console.log("got here")` right before the Ajax call and see if you see that in the debug log when you click the submit button in the form. This will tell you whether your `.submit()` handler is even being called and will tell you where to look next. – jfriend00 Oct 07 '14 at 04:31
  • jfriend00's advice had me realize that the form was being rested inside a larger function (didn't realize it). Tired eyes. Thanks everyone for the help! jFriend00 if you want to make this comment into an answer, I'll mark it correct – Splashlin Oct 07 '14 at 04:34

2 Answers2

2

Posting as an answer per the OP's request since this led to the answer.

Change your first line of code to:

$('#contact_form').submit(function() {  

to match the id value in your HTML.

Then, do some elementary debugging. Put a console.log("got here") right before the Ajax call and see if you see that in the debug log when you click the submit button in the form. This will tell you whether your .submit() handler is even being called and will tell you where to look next.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

a few things pops into my mind while looking at your code which may be causing this problem:

As explained by jfriend00 in the comments #2 and #3 are not the problem

  1. $('contact_form') refers to the element <contact_form>. does it exist or is it intended to refer to a class $('.contact_form') or id $('#contact_form')?
  2. in the line url: $(this).attr('action') $(this) doesn't actually exist, so you need to define a variable before the ajax call and store this in it. var that=this and then change the line to url: $(that).attr('action')
  3. return false is actually not the best way to prevent the default action of the event, the better way would be to use .preventDefault()

In the end your code may look something like this: (assuming the contact_form is an id)

$('#contact_form').submit(function(e) {
    e.preventDefault();  
    var valuesToSubmit = $(this).serialize();
    var that=this;
    $.ajax({
        url: $(that).attr('action'),
        data: valuesToSubmit,
        dataType: 'json',
        type: 'POST',
        success: function(data) {
            alert('success');
        },
        error: function(data) {
            alert('error');
        }
    });
});
Amin Jafari
  • 7,157
  • 2
  • 18
  • 43
  • Your #1 is definitely the first problem - it needs to be `$("#contact_form")` according to their HTML. #2 is not something that needs to be changed. It should work as is because `this` is before calling the ajax function so it will be the `form` object. #3 will also work just fine. returning false will do both `.preventDefault()` and `.stopPropagation()` which is fine here. – jfriend00 Oct 07 '14 at 04:28
  • Tried all of these and unfortunately nothing worked. I updated #1 to use $('form#contact_form') but didn't change the behavior. – Splashlin Oct 07 '14 at 04:28
  • @AminJafari - there are no probabilities with working vs. non-working code. The code for #2 and #3 works just fine - no need to change. No probabilities involved. – jfriend00 Oct 07 '14 at 04:33
  • @Splashlin just one thing, while using ajax to submit your form, you're not gonna need `action` or `method` for your form in the HTML since it is set later in your ajax call. also does `contact_message` handle the call correctly? I think you need to define a suffix for your file (e.g. `contact_message.php`) – Amin Jafari Oct 07 '14 at 04:34
  • @jfriend00 but I've seen a lot of questions about `return false` not working (http://stackoverflow.com/questions/18335408/jquery-return-false-on-submit-not-working-form-still-submits) and also `this` not being recognized in the ajax call (http://stackoverflow.com/questions/8186969/jquery-ajax-this-id-undefined) – Amin Jafari Oct 07 '14 at 04:36
  • 1
    @AminJafari - yes `this` will not necessarily be the right value inside the `success` or `error` handler, but it is guaranteed to be the right value BEFORE the Ajax call which is where it was being used. Your reference about `return false` is just wrong. When you do a `return false` from any Ajax event handler it does both an `event.preventDefault()` and an `event.stopPropagation()` which are absolutely fine in this case. Right in the jQuery doc for `.submit()`, it says that returning `false` is a perfectly acceptable way to prevent the default form submission. – jfriend00 Oct 07 '14 at 04:43
  • @jfriend00 well, thanks for clarification, and thanks for teaching me a new thing ;) – Amin Jafari Oct 07 '14 at 04:45
  • @jfriend00 but just in case others may learn the thing that I learned while reading these comments, I leave those numbers un-removed. – Amin Jafari Oct 07 '14 at 04:47