user1885868 user1885868 - 5 months ago 7
Javascript Question

Saving file to server using PHP and Javascript

I have a data string in Javascript and I would like to store it in a text file in my server.

The normal thing to do is to send the data to a PHP medium file to process it and do the file storage part.

This is the code I used but it looks like it doesn't run at all as the destination file

matrice.txt
is still blank :

script.js

function finalCoords() {

for(var i = 0; i < sort_data.length; i++) {
matrix = [data.nodes[i].name, sort_data[i].x, sort_data[i].y, sort_data[i].z]; /* This data is collected from other arrays */
var matrixStr = matrix.join(" "); /* This is the string I want to store */
console.log(matrixStr);

$.ajax({
url: "matrice.php", /* This is the PHP Medium */
data : matrixStr,
cache: false,
async: true,
type: 'post',
timeout : 5000
});
}
}


matrice.php

<?php
$file="matrice.txt"; /* This is the destination file */
$text=serialize($_POST);
$fh = fopen($file, 'a') or die();
fwrite($fh, $text."\n");
fclose($fh);
?>


What is the problem and how can I fix it ?

Thanks!

Answer

First thing to note: You're calling the callback as many times as there are elements on sort_data array, which I believe it's not the intended functionality.

Also, you should really check if your ajax() call was successful or not. Ajax call has a parameter method (instead of type) according to the documentation.

Finally, you could write to a file with a one-liner...

So, let's put it all together:

script.js

function finalCoords() {
  var matrix = [];
  for(var i = 0; i < sort_data.length; i++) {
    matrix.push([data.nodes[i].name, sort_data[i].x, sort_data[i].y, sort_data[i].z]); /* This data is collected from other arrays */
  }
  var matrixStr = matrix.join(" "); /* This is the string I want to store */
  console.log(matrixStr); 

  $.ajax({
    url: "matrice.php", /* This is the PHP Medium */
    data: matrixStr,
    cache: false,
    async: true,
    method: 'POST',
    timeout : 5000
  })
  .done(function() {
    console.log("success");
  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    console.log("complete");
  });
}

matrice.php

<?php
    $file = "matrice.txt"; /* This is the destination file */
    $text = serialize($_POST);
    file_put_contents($file, $text);
?>

That should do the trick and tell if there are any errors with the ajax call.

EDIT

Taking a cue from the comment from charlietfl (thanks, btw), we should take the raw post data:

<?php
    $file = "matrice.txt"; /* This is the destination file */
    $text = file_get_contents('php://input');
    file_put_contents($file, $text);
?>
Comments