I am trying to save an JSON encoded array to an existing text file on the server.
Here is the html code. When I click the button nothing seems to happen and I am not getting any error messages in the console.
And here is what I have so far for the receive.php file.
Any help would be appreciated in understanding what I am doing incorrectly. If this is a php problem, then I can post this in that forum. Thanks.
Here is the html code. When I click the button nothing seems to happen and I am not getting any error messages in the console.
HTML:
<body>
<button class="button" id="save-data" >Save Data</button>
<script>
var button = document.getElementById("save-data");
button.addEventListener("click", function(){
var tbldata = [{"id":1, "name":"Bob"}]
var request= new XMLHttpRequest();
request.open("POST", "receive.php");
request.setRequestHeader("Content-type", "application/json");
request.send(tbldata);
});
</script>
</body>
And here is what I have so far for the receive.php file.
PHP:
<?php
if(isset($_POST['tbldata'])){
$data = $_POST['tbldata'];
//Save the JSON string to a text file.
file_put_contents("names.txt", $data);
}
?>
Any help would be appreciated in understanding what I am doing incorrectly. If this is a php problem, then I can post this in that forum. Thanks.