Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly escape html sent as data in jQuery's .ajax function

UPDATE: Once I looked at the problem in Firebug, I found my mistake immediately. And it was an embarrassing unmatched double quote that I must have deleted somehow. I had been using Chrome's developer window. Very sorry for using up your resources. But, lesson learned! ("I hope.)

What is the best way for me to escape html characters that I want to send to my server? I am using jQuery, .ajax(), and jsonp.

I'm writing a bookmarklet which sends parts of the current page's html to my server. Here is the ajax call:

jQuery.ajax({
    url: 'http://www.my_server.com/file.php?callback=?',
    dataType: 'jsonp',
    data: { someHtml: escape(jQuery(this).html().substring(0,1000)) },
    success: function() { // stuff },
    beforeSend: function(xhr) {
                  xhr.setRequestHeader('Content-type','text/html');
                },
    error: function() { // stuff }
});

I need to use JSONP and therefore I can't use POST, and this is why I'm truncating the html data. Things work if the html is "nice", but if it contains characters javascript doesn't like, then I have problems. I fixed my ' problem by using escape(), but now I think I'm having newline and tab problems.

Chrome's dev console gives me the same error:

Uncaught SyntaxError: Unexpected token <

which I assume means some character is causing things to break out of javascript. I have tried the following: escape(), encodeURI/Component(), serialize(), text(), but nothing has worked yet. At first, I didn't use beforeSend, but thought I should try it, but no difference.

Currently, I'm stuck with some html which has a line break, then a tab, then a couple of spaces. I have tried replacing these characters using replace():

... .substring(0,1000).replace(/(\r\n|[\r\n])/g,'')

I found this regex string on another site which is supposed to replace various combinations of carriage returns and line feeds.

I hope I've explained myself clearly enough. It's my first question at Stack Overflow so go easy on me. :)

like image 269
SeanO Avatar asked Nov 08 '10 08:11

SeanO


1 Answers

You don't need to escape or encode. jQuery will take care of properly URL encoding the data:

data: { someHtml: $(this).html().substring(0, 1000) },
like image 111
Darin Dimitrov Avatar answered Nov 12 '22 19:11

Darin Dimitrov