Error sending string via ajax to php that writes it to a text file

0

Here is the code js:

$.ajax({
            type: "POST",
            url: "./ladderboard.php",
            data: {
                "json": JsonString
            },
            success: function(data) {
                alert(data);
                alert(JsonString);
            }

        });

And the php code:

<?php 
  $json = $_POST["json"];
  $file = fopen("archivo.txt", "w");
  fwrite($file, $json  . PHP_EOL);
  fclose($file);
?>

The error that it gives me in console is that it does not recognize the chain that I am sending to it through the POST method.

All possible help would be appreciated.

    
asked by Juankaxx 28.02.2018 в 14:13
source

1 answer

0

It seems to me that the way you try to create your JSON is impractical, if not incorrect.

Here I show several possible ways to do it. For more ease it would be convenient to put all the data you want in a form .

In the first option you will create a proper JSON (I would use that form preferably), since the second form creates you a JSON Array. It is also valid, but the JSON object will be found in the index 0 of the array.

var $frm = $("#myform");

/*1ª forma: Objeto JSON propiamente dicho*/
var json = formToJSON($frm);
console.log(json);

function formToJSON($form) {
  var arrSerialize = $form.serializeArray();
  var arrNew = {};

  $.map(arrSerialize, function(n, i) {
    arrNew[n['name']] = n['value'];
  });

  return arrNew;
}

/*2ª forma: Array JSON*/
var data = JSON.stringify($frm.serializeArray());

console.log(data);

/*3ª forma: Objeto JSON manual*/
var jsonManual =
  '{"nombre":"' + $("#nombre").val() + '",' +
  '"puntos":"' + $("#puntos").val() + '"}';
console.log(jsonManual);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
  <input id="nombre" name="nombre" value="nombre test" />
  <input id="puntos" name="puntos" value="10" />
</form>

As for PHP, keep in mind that the use of fopen with w places the pointer at the beginning of the file, rewriting it. If you want to continue adding content, you can use a . For more details you can see here and in the PHP Manual there is a wider list of all the possibilities offered by fopen .

    
answered by 28.02.2018 в 15:26