Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Send array data to text file on click of button 1

Status
Not open for further replies.

waubain

Technical User
Dec 13, 2011
200
US
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.

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.

 
Hi

That way tbldata gets cast to string, so "[object Object]" is sent to the server. You can either
[ul]
[li][tt]JSON.stringify()[/tt] it -- in PHP you will be able to read it from [tt]php://input[/tt][/li]
[li]convert to URL encoded string -- in PHP you will get it in [tt]$_POST[/tt], but of course still nothing name "tbldata"[/li]
[/ul]


Feherke.
feherke.github.io
 
Feherke,

Thanks for the help. I got the first solution to work.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top