Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to bind ajax:success to form created with form_for .... :remote => true

I'm using Rails 3.1.1

I have the following in a haml view:

= form_for booking.notes.build, :remote => true do |f|
  = f.text_area(:content)
  = f.hidden_field(:noteable_id)
  = f.hidden_field(:noteable_type)
  = f.submit('Add note')

Which creates new notes on submission. Also the response from my controller is appearing correctly in a Chrome console (Network tab). But I cannot seem to grab the response.

I want to update the note list on the page after submission. I've been trying to bind to the ajax response so I can grab the response, but I am failing. For example, I think this should work but does not:

$('#new_note').bind('ajax:success', function() {
  alert('Hi');
});

But no alert is triggered. Which I think explains why this also doesn't work.

 $('#new_note').bind("ajax:success", function(evt, data, status, xhr){
  // Insert response partial into page below the form.
  $(this).parent.append(xhr.responseText);

})

Can you please point me as to what might be going wrong?

like image 897
11 revs, 10 users 40% Avatar asked Mar 16 '12 15:03

11 revs, 10 users 40%


2 Answers

Did you try 'ajax:complete'?

Other things that can go wrong here:

Status code was not really "successful". This triggers success in jQuery

if ( status >= 200 && status < 300 || status === 304 ) {

Or the event handler was evaluated before the form was rendered. Try event delegation:

$("body").on('ajax:success', '#new_note', function(){...})

(careful, this is the new jQuery syntax. If using old jQuery, adjust accordingly)

like image 190
egze Avatar answered Oct 16 '22 14:10

egze


if you want, you can put your javascript in create.js.erb (code in this file will be executed after response will come to your browser) And in this file you can use if statement, like

<% if @ok %>
  //your code
<% end %>

if in your controller's action set @ok to false the response will be empty!

like image 24
ibylich Avatar answered Oct 16 '22 14:10

ibylich