JQuery AJAX: How to pass large HTML tags as parameters?

How to transfer big HTML tag data to my PHP using jQuery AJAX? When I get the result, this is wrong.

JQuery AJAX Code :

$('#saveButton').click(function() { // do AJAX and store tree structure to a PHP array //(to be saved later in database) var treeInnerHTML = $("#demo_1").html(); alert(treeInnerHTML); var ajax_url = 'ajax_process.php'; var params = 'tree_contents=' + treeInnerHTML; $.ajax({ type: 'POST', url: ajax_url, data: params, success: function(data) { $("#show_tree").html(data); }, error: function(req, status, error) { } }); }); 

actual value of treeInnerHTML :

 <ul class="ltr"> <li id="phtml_1" class="open"> <a href="#"><ins>&nbsp;</ins>Root node 1</a> <ul> <li class="leaf" id="phtml_2"> <a href="#"><ins>&nbsp;</ins>Child node 1</a> </li> <li class="last leaf" id="phtml_3"> <a href="#"><ins>&nbsp;</ins>Child node 2</a> </li> </ul> </li> <li id="phtml_5" class="file last leaf"> <a href="#"><ins>&nbsp;</ins>Root node 2</a> </li> </ul> 

The returned result from my show_tree div :

 <ul class="\&quot;ltr\&quot;"> <li id="\&quot;phtml_1\&quot;" class="\&quot;open\&quot;"> <a href="%5C%22#%5C%22"><ins></ins></a> </li> </ul> 
+6
jquery ajax
source share
3 answers

See if changing parameters from a string to an object helps:

 var params = { tree_contents: treeInnerHTML }; 

See http://jsfiddle.net/7bF2Y/

+5
source share
 var params = 'tree_contents=' + encodeURIComponent(treeInnerHTML); 

TreeInnerHTML is disabled on the first character & (since the POST data uses the format var1=val&var2=val2&... ), the rest of the resulting HTML is your browser that automatically closes the closed tags.

+4
source share

You pass the value without URL encoding, so it probably won't be parsed correctly on the server. As Salman A said, you should get jQuery to take care of this for you, passing the dictionary instead:

 var params = { tree_contents: treeInnerHTML }; 
+1
source share

All Articles