I have a button with remote=>true that calls a popup (a jquery popup, not a real one) in the following way:
$modal = $('#modal')
$modal_close = $modal.find('.close')
$modal_container = $('#modal-container')
$task_select_div = $('.activity_task_add')
# Handle modal links with the data-remote attribute
$('a[data-remote]').on 'ajax:success', (xhr, data, status) ->
$modal
.html(data)
.prepend($modal_close)
.css('top', $(window).scrollTop() + 150)
.show()
#This is the callback that is not being executed.
$('form[data-remote]').on 'ajax:success', (xhr, data, status) ->
alert(data)
$modal_container.hide()
$modal.hide()
$task_select_div.html(data)
In that popup I have another form with remote_tag in the submit button of this form I call and action that has the following code at the bottom:
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render json: @task, status: :created, location: @task }
format.js {render :partial => 'tasks', :locals => {:tasks => current_user.department.tasks}}
else
format.html { render action: "new" }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
It executes format.js and the console says "Rendered tasks/_tasks.html.erb (5.8ms)" but the callback for the ajax call is not working.
$('form[data-remote]').on 'ajax:success', (xhr, data, status) ->
alert(data)
I need to receive an ajax:success event in order to hide the Popup. Any help?
Remove this line :
format.js {render :partial => 'tasks', :locals => {:tasks => current_user.department.tasks}}
Update your js callback :
$('form[data-remote]').on 'ajax:success', (xhr, data, status) ->
alert("hello world")
$modal_container.hide()
$modal.hide()
$task_select_div.html(<%= escape_javascript(render :partial => 'tasks', :locals => {:tasks => current_user.department.tasks} ) %>)
Solved it.
Changed my respond_to do |format| for this:
if request.xhr?
task_list = render_to_string :partial => 'tasks', :locals => {:tasks => current_user.department.tasks}
task_list = task_list.html_safe.gsub(/\n/, '').gsub(/\t/, '').gsub(/\r/, '')
render :json => {:html => task_list, :error => ''}
else
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render json: @task, status: :created, location: @task }
else
format.html { render action: "new" }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
And my javascript for this:
$('form[data-remote]').on 'ajax:success', (xhr, data, status) ->
$modal_container.hide()
$modal.hide()
$task_select_div.html(data.html)
What do you think of this solution? Any drawbacks?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With