views:

84

answers:

2

I'd really like to take all of the html in a div (contains many other divs, form elements, etc), urlencode it (maybe) and then do an ajax post to a server side handler so that I can save the exact state of what the user is seeing.

I would then like to be able to take that string that I've saved in a database and send it back in response to an ajax call in the future.

Should I use something like the following?

var contents = escape($('#myDiv').html());

Then do an ajax post operation to a server side handler? Would escape ensure that I am not passing back any special characters that would mess up the ajax call?

Any pointers are appreciated.

+1  A: 

I'm using this:

function htmlEncode(value){ return $('< div / >').text(value).html(); }

function htmlDecode(value){ return $('< div />').html(value).text(); }

var contents = htmlEncode($('#myDiv').html());

pashaweb
+2  A: 

You don't have to worry about escaping the data if you're sending it as a POST parameter. If it was a GET, it would actually be appearing in the URI and you would need to make sure everything was escaped.

This is all you really need to do:

$.post('/my_handler', {'html': $('#myDiv').html()}. function(data){
     //do something with data     
});

Your script responding at /my_handler will just need to check the 'html' post parameter for that string. For example, if you're using PHP you would just check $_POST['html'].

joeynelson