Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Data to File via Ajax POST and PHP

Tags:

jquery

ajax

php

I just want to save some JSON (generated with Javascript) in a file on the server. But I even don't get it to work with a simple string:

HTML File:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style>
#test{
padding:20px 50px;
background:#ccc;
color:#000;
}
</style>
<script>
$(function(){
$('#test').click(function(){
    $.ajax({
        url: "page.php",
        data: {"foo": "bar"},
        processData: false,
        contentType: 'application/json'
    });

});
});
</script>
</head>
<body>

<div id="test">
KLICK
</div>
</body>
</html>

And the php file is something like this:

<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fwrite($fh,$_POST['data']);
fwrite($fh,$_POST['foo']);
fwrite($fh,$_POST["foo"]);
fwrite($fh,$_POST[foo]);
fclose($fh);

Nothing worked. I also tried

$.ajax({
    var datatosend="foo bar";
    url: "page.php",
    data: datatosend,
    processData: false
    });

I don't know what could be wrong. The txt file is there after clicking the div in the html file. But there is no content in the file. If I just write $_POST to the text file, the file contains the Text "Array", meaning that $_POST has some content.

like image 459
Jens Avatar asked Nov 03 '22 17:11

Jens


1 Answers

Few things could be going wrong here. Check the permissions on the directory your are trying to write to. Also make sure that your ajax call is using the POST method.

$.ajax({
  url: "page.php",
  type : 'POST',
  ...
}); 

As sated in the jQuery documentation, the type parameter sets the request type, POST or GET.

The type of request to make ("POST" or "GET"), default is "GET".


Another thing to consider is that you are not actually writing JSON data. The data is send in that format but when it gets to the $_POST variable it has been converted into an array. What you should try doing is writing a PHP array to the file -

$fh = fopen($myFile, 'w');
fwrite($fh,'<?php $arr='.var_export($_POST['data'],true).' ?>');
fclose($fh);

That should give a file similar to this -

<?php
  $arr = array(
    'foo'=>'bar'
  )
?>

As you can see, the var_export() function returns a parsable version of the variable.

  • var_export()

var_export — Outputs or returns a parsable string representation of a variable

like image 57
Lix Avatar answered Nov 15 '22 05:11

Lix