Reputation: 557
I am trying to take data from my div an add it to php file: my javascript is:
$(document).ready(function(){
$('#save').on('submit',function(e) {
var bufferId = document.getElementById('data2save');
$.ajax({
url:'saver.php',
data:{id : bufferId},
type:'POST',
success:function(data){
console.log(data);
alert("ok"); //=== Show Success Message==
},
error:function(data){
alert("not ok"); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
my html part is:
<input type="button" value="save" id="save">
<div id="data2save">
Data to be added.
</div>
and my saver.php file is:
<?php
$data = $_POST['id'];
if (($fp = fopen("test.txt", "w"))){
fwrite($fp,$data);
fclose($fp);
echo "ok";
}
?>
Can someone please point out the issue?
Upvotes: 1
Views: 2006
Reputation: 136
As document.getElementById('data2save') is an DOM element. You cannot sent it directly as data in the AJAX request.
Replace it with document.getElementById('data2save').value and then let us know if it works.
The new javascript would be like this
(document).ready(function(){
$('#save').on('submit',function(e) {
var bufferId = document.getElementById('data2save').value;
$.ajax({
url:'saver.php',
data:{id : bufferId},
type:'POST',
success:function(data){
console.log(data);
alert("ok"); //=== Show Success Message==
},
error:function(data){
alert("not ok"); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
Upvotes: 0
Reputation: 6567
Your have a wrong selector, replace document.getElementById('info1');
with var bufferId = $("#data2save").html();
$(document).ready(function(){
$('#save').on('submit',function(e) {
var bufferId = $("#data2save").html();
$.ajax({
url:'saver.php',
data:{id : bufferId},
type:'POST',
success:function(data){
console.log(data);
alert("ok"); //=== Show Success Message==
},
error:function(data){
alert("not ok"); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
Upvotes: 1