Rails 3- partial partial renderer for ajax call inside popup

I have a button with remote => true that calls a popup (jQuery popup, not real) like this:

$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 this popup, I have another form with remote_tag in the submit button of this form that I invoke and an action that has the following code below:

 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 ajax call does not work.

 $('form[data-remote]').on 'ajax:success', (xhr, data, status) -> alert(data) 

I need to get the ajax: success event to hide the popup. Any help?

+4
source share
2 answers

I decided.

Changed my reply_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 decision? Any flaws?

+1
source

Remove this line:

 format.js {render :partial => 'tasks', :locals => {:tasks => current_user.department.tasks}} 

Update 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} ) %>) 
+1
source

Source: https://habr.com/ru/post/1393179/


All Articles