Saving data to a file through AJAX POST and PHP

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

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 looks 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 succeeded. I also tried

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

I do not know what might be wrong. The txt file is located after clicking div in the html file. But there is no content in the file. If I just write $ _POST to a text file, the file contains the text "Array", which means that $ _POST has some content.

+5
source share
4 answers

Few can make a mistake here. Check the permissions in the directory you are trying to write to. Also make sure your ajax call uses the POST method.

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

jQuery, type , POST GET.

( "POST" "GET" ) - "GET".


, , , JSON. , $_POST, . , PHP -

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

, -

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

, var_export() .

var_export -

+2

POST, . :

$('#test').click(function(){
    $.ajax({
        url: "page.php",
        type : 'post', 
        data: {"foo": "bar"},
        processData: false,
        contentType: 'application/json'
    });

});
0

$.ajax() GET, POST. "POST":

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

:

type - String

: 'GET'

Type of request ("POST" or "GET"), by default - "GET". Note: Other HTTP request methods may also be used, such as PUT and DELETE here, but they are not supported by all browsers.

0
source

Maybe it should be

    $.ajax({
    url: "page.php",
    type: "POST", // add this
    data: {"foo": "bar"},
    processData: false,
    contentType: 'application/json'
});

OR

in PHP use $_REQUESTinstead$_POST

0
source

All Articles