How do I send HTML through an Ajax call?

October 15, 2012

This scenario stated when I tried sending html to a file that would then email the requested html to a user. I’m sending two variables, one that has html text and an email address. The variables transfer fine, but to my dismay, the styles and images wouldn’t show up and the html didn’t look quite right.

A typical ajax call would look like this:

$.ajax({
	   type: 'POST',
	   url: ' /requestlink.php',
	   data: { html: html, email: email },
	   success: function(response){ alert('success'); } 
	});

The solution was to encode the string with encodeURIComponent before sending it over.

$.ajax({
	   type: 'POST',
	   url: ' /requestlink.php',
	   data: { html: encodeURIComponent(html), email: email },
	   success: function(response){ alert('success'); } 
	});

Now that you have a string of unicode characters, you would decode within the request link with decodeURIcomponent. **in php, it’s urldecode(string)

Author

Stay in Touch!

Stay in Touch!
Solutions Architecture

browse through our blog articles

Blog Archive