Papa De Beau
Papa De Beau

Reputation: 3828

jQuery get div contents and send to php script via ajax

I am trying to get the contents of a div and send that to ajax.

Here is a sample code of ajax that sends data but how can I put the html contents of a div in this post and send it to another php script via ajax?

I need to send ALL the HTML in the "sortable" ui and not just the text.

<ul id="sortable">

<li class="ui-state-default">Hello, please send me to Ajax! :)</li>

</ul>


$("button").click(function()
  {
      $.post("get_sorted_content.php", // Example script
      {

       data: $("#sortable").html(); // My NEEDED content - Does not work!

     function(data)
       {

       alert("Data: " + data + ");
       });
 });

Again, This code may be missing some elements but regardless it doesn't work. It's just an example showing what I am trying to do.

Upvotes: 1

Views: 3632

Answers (2)

TheVillageIdiot
TheVillageIdiot

Reputation: 40507

Your $.post call needs to change as follows:

$.post('get_sorted_content.png', 
          { data: $("#sortable").html()},
          function(data){
              //data is whatever you send back from php script.
          }
      );

if $("#sortable").html() does not work, try to escape the HTML like:

escape($("#sortable").html());

Upvotes: 2

scrowler
scrowler

Reputation: 24406

I'll use the AJAX method as an example here because I think it's a little clearer about what you want to do. Let's retrieve the li contents and sent it to your PHP script.

Don't bind to the button element, that is not very specific at all and will bind to any button on the page. Instead, give it an id and bind to that.

Your main problem is that you're getting the HTML of the ul with id sortable, not the specific li element you're after.

<ul id="sortable">
    <li class="ui-state-default">Hello, please send me to Ajax! :)</li>
</ul>

<button id="clickme">Click me!</button>

// bind to the button with clickme ID
$("button#clickme").click(function() {
    $.ajax({
        url: 'get_sorted_content.php',
        type: 'POST', // GET is default
        data: {
            yourData: $('#sortable li').html()
            // in PHP, use $_POST['yourData']
        },
        success: function(msg) {
            alert('Data returned from PHP: ' + msg);
        },
        error: function(msg) {
            alert('AJAX request failed!' + msg);
        }
    });
});

Now in your PHP script, you can access that data with $_POST['yourData']:

<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
    echo 'data received!';
else
    echo 'no data received!';
?>

EDIT: following having seen your statement: I need to send ALL the HTML in the "sortable" ui and not just the text., if you need the entire ul contents, use what you had originally:

data: {
    yourData: $('ul#sortable').html();
}

Upvotes: 2

Related Questions