How to make an ajax request that returns an html text?

Asked

Viewed 303 times

2

Assuming the link making the request is:

<%= link_to 'New Classroom', new_classroom_path,class: :remote_link, remote: true %>

And may the treatment of the return of the same be:

$('.remote_link').bind('ajax:success',function(e, data, status, xhr) {
    ajax_replace(data.responseText, status, xhr)
  });

function ajax_replace(data, textStatus, request)
{
    replace_html(data,request.getResponseHeader("content_id"));
}

In which the returned html text replaces the html text found in the div that has the same id as the one stored in the "content_id header"

The method that enters the request on the server is:

after_filter :set_featured_id

def new
    @classroom = Classroom.new
    respond_to do |format|
      format.js{render :new, formats: [:html]; head :ok}
    end  
end 

def set_featured_id
    response.headers['content_id'] = 'featured'
end

Where a method includes the required value in the header after the processing.

The problem is that although the value set in the header is recovered correctly, the rendered value is not found as responseText.

  • It wouldn’t be something like data.body and not date.responseText?

  • @user5020, I believe responseText is a property of jqXHR xhr and not of PlainObject data . then try to use xhr.responseText, in any case, try to make a full example, including with the request AJAX, you can simulate one using a memory URL, as in the following Jsfiddle

1 answer

1


do not need to use the js format, use html and leave the layout as false

#exemplo
format.html{ render '/products/new', layout: false } if request.xhr?

ai when receiving the response from the server it will send exactly the content that is in new.html.erb less the layout of the page, if I understood it is that you want right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.