Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 - ajax form ajax:success event not being called

After much troubleshooting, I am not able to figure out why my form's ajax:success callback is not being called in rails 3.

Following is the code ultimately generated in my view:

JS Code:

$(function() {
  $("#myform").bind('ajax:success', function(data, status, xhr) {
    alert("form success");
    console.log(data);
    console.log(status);
  }).bind('ajax:error', function(xhr, status, error) {
    console.log(error);
    console.log(status);
  });
});

Ajax Form:

<form accept-charset="UTF-8" action="/myc/mya" data-remote="true" id="myform" method="post">       <div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="hZuhxwboQj2qo8MPIR8DWwYMqAC1V2yqG+DX9UnlIr0=" /></div>
          <input class="large" id="foo" name="foo" type="text" />
        <input class="btn success" data-disable-with="Working..." name="commit" type="submit" />
        </form>

Following the logic that happens in the action which the form posts to:

 @foo = { :foo => "bar" }
 render(:json => @foo.to_json, :content_type => 'application/json',
        :layout => false)

I have Firebugged this entire request/response:

It says 200 OK. And the Response Headers are:

Cache-Control   max-age=0, private, must-revalidate
Connection  Keep-Alive
Content-Length  13
Content-Type    application/json; charset=utf-8
Date    Mon, 23 Jan 2012 10:37:19 GMT
Etag    "9bb58f26192e4ba00f01e2e7b136bbd8"
Server  WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Set-Cookie  _session_id=BAh7CkkiD3Nlc3Npb25faWQGOgZFRiIlMGIzZGRhZDQ2ZjNmYzUzOWJkMzBkZWMxZDBmMDgwODZJIhBfY3NyZl90b2tlbgY7AEZJIjFoWnVoeHdib1FqMnFvOE1QSVI4RFd3WU1xQUMxVjJ5cUcrRFg5VW5sSXIwPQY7AEZJIhJyZXF1ZXN0X3Rva2VuBjsARkkiMGlCVmFZYllrU2R1RHl2aVZ4ZGc3ZWxKdmVxZkdFa1VKYWVXaHU0eXBmR1kGOwBUSSIZcmVxdWVzdF90b2tlbl9zZWNyZXQGOwBGSSIwcFdGTUVTUGt6d2VSY1pzV2YxU3JLNmFJSEpCU3FGMDh2ZmZ2U0pFaVI4cwY7AFRJIhRjdXJyZW50X3VzZXJfaWQGOwBGSSIpZDZiZDdhMjYtNDRjNi0xMWUxLTkwMDItZmExMjJjNjJmZTFmBjsARg%3D%3D--78099c697506ede3c7e9a833efa1785c6f1b9a6e; path=/; HttpOnly
X-Runtime   0.354051
X-Ua-Compatible IE=Edge

The response is, as expected:

{"foo":"bar"}

200 OK response should trigger 'ajax:success' in my JS... but this is not happening. Any thoughts? The error callback is not being hit either...

like image 236
deruse Avatar asked Jan 23 '12 10:01

deruse


1 Answers

I had this same issue. After 90 minutes of searching I finally got it to work by using the following:

$(document).on('ajax:success', '.delete', function(e) {
    $(e.currentTarget).closest('div').fadeOut();
});

Credit to: https://stackoverflow.com/users/1609186/ivan-fong

I was creating and then trying to delete what I had just created, all via ajax requests. hope this can help someone.

like image 124
user1371138 Avatar answered Nov 15 '22 22:11

user1371138