Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

How can I pass a large HTML tag data to my PHP using jQuery AJAX? When I'm receiving the result it 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) { }
        });
});

treeInnerHTML actual value:

<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>

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>
like image 716
marknt15 Avatar asked May 14 '10 06:05

marknt15


2 Answers

var params = 'tree_contents=' + encodeURIComponent(treeInnerHTML);

TreeInnerHTML is being cut off at the first & mark (since POST data uses var1=val&var2=val2&... format), the rest of the resulting HTML is your browser automatically closing unclosed tags.

like image 171
Tgr Avatar answered Nov 15 '22 05:11

Tgr


See if changing params from an string to an object helps:

var params = { tree_contents: treeInnerHTML };

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

like image 20
Salman A Avatar answered Nov 15 '22 07:11

Salman A