user1276919
user1276919

Reputation: 558

Save content of a div to new file with jQuery AJAX and PHP

I'm trying to save contents of a div to new html file. I'm using jQuery AJAX to send data to php.
However, the php in its current form writes an empty file.

Html:

<div id="data2save">
     <span>data1</span>
     <span>data2</span>
     <span>data3</span>
     <span>data4</span>
</div>

<input type="button" value="save" id="save">

JQuery:

 $("#save").live("click",function() {

    var bufferId =$("#data2save").html();

            $.ajax({
                 method : "POST",
                 url : "saver.php",
                 data: {id : bufferId},
                 dataType: "html",
                 success: function(data){ 
                 alert("ok");  
                 }
                 });
 });

PHP:

 <?php
$handle = fopen("test.html", 'w+');
$data = $_POST['data'];
if($handle)
{

if(!fwrite($handle, $data ))
echo "ok";
}

?>

Upvotes: 3

Views: 4611

Answers (2)

Silviu-Marian
Silviu-Marian

Reputation: 10907

Request method property is type instead of method ($.ajax({ method : "POST" is actually $.ajax({ type : "POST") and $_POST['data'] should be $_POST['id'].

Upvotes: 5

Abel Mohler
Abel Mohler

Reputation: 794

There is no $_POST['data'] being posted, only $_POST['id']. Look at this part:

data: {id : bufferId},

Upvotes: 1

Related Questions