views:

117

answers:

1

So I am trying to use jQuery to insert data from an ajax call.

I actually use the jquery.form plugin, and have the ajax form submitted with a dataType: 'script'.

The response is a jquery expression which contains a <%= javascript_escape(render ...) %> erb tag (similar to what the railscasts episode 136 instructs to do). However the end result is that the full text of the render is inserted as if that was the content to be inserted into the page, as text, not as dom elements.

Could the fact that the render had some newlines at the beginning be the cause?

Dom text: "\n \n &lt;li>....&lt;/li>"

I also tried having jQuery just read the response as a script and execute it, and used the prototype-based rjs stuff, same effect, the text is inserted into the dom. Are there any reasons why such a behavior would be experienced?

A bit of clarification:

My response.js.erb is

jQuery("#content").append("<%= escape_javascript(render(:partial => "widgets")) %>");
jQuery("#information").text("Finally, something happened!");

The full text inside the append() call is inserted as text into #content.

Update:

I've been doing some research into the problem. Turns out the reason why rails is escaping the <> characters is because it thinks it is rendering a regular .html file. The reason being that it has no indication that a .js is coming, because the post is done using an iframe (the post contains a file). If I add a .js to the end of the request I can do a respond_to do |format| format.js however it does not support http posts. Is there a way to configure it to accept posts on a .js request for an action?

+1  A: 

I'd guess it's because you have dataType set to 'script'. If you want the results of the AJAX call to be treated as DOM elements, change that to HTML.

It also depends on how you're inserting the results into the document. I doubt this is the case, but if you're using .text() rather than .html(), you'll get plain text rather than DOM elements.

Pickle
Not quite, I've considered changing the response to HTML and just having my script inject it to where appropriate, I wanted a more RJS style behavior though. See my clarification.
Dmitriy Likhten
Looks like this will have to be the acceptable answer. Rails does not appear to support rendering an erb template without doing HTML entity escaping. Thus when the output is sent to an iframe, everything is escaped and unusable.
Dmitriy Likhten