jQuery ajax multiline "script" response
Posted
by Rendrik
on Stack Overflow
See other posts from Stack Overflow
or by Rendrik
Published on 2010-05-19T16:31:29Z
Indexed on
2010/05/30
6:22 UTC
Read the original article
Hit count: 225
I'm designing a template creation tool, which uses a jQuery Ajax request that posts parameters to a PHP file. The PHP does the actual generation of the template's HTML.
// Send for processing. Expect JS back to execute.
function generate() {
$.ajax({
type: "POST",
url: "generate.php",
data: $('#genform :input').serialize(),
dataType: "script",
beforeSend: function() {
$("#loading").html("<img src='images/loadbar.gif' />");
$("#loading")
.dialog({
height: 80,
width: 256,
autoOpen: true,
modal: true
});
},
success: function(data) {
$("#loading").dialog('close');
}
});
}
My trouble is that I have the ajax dataType: set to "script". Using this, the PHP file generates some jQuery dialogs for any errors which works nicely. However, after I generate the HTML, i'm having trouble passing it back.
So I have probably 100 lines of generated HTML and javascript which i'd like to work with. In the PHP file, i've tried:
echo('$("#result").html("'.$html.'");');
This does actually work if there are NO line breaks in $html. As soon as there are any line breaks, the Chrome debugger reports "gen.html:1 Uncaught SyntaxError: Unexpected token ILLEGAL". It's obvious that it's trying to eval the returned response headers, but is stopping at any line break.
So, to be clear, when I pass $html back, if the contents are this:
$html = "<div>hi there</div>";
It works fine (all of my error message dialogs are one line). But if it's:
$html = "<div>
hi there
</div>";
It blows up.
I'm really not sure how to get around this, or if there's a better way to go about it. It's important to me to keep the formatting so people can copy the HTML template.
I may just break down and display the template file on the PHP page if I can't solve this, but I was really hoping to keep everything within the confines of the HTML page.
© Stack Overflow or respective owner