0

I have a variable in javascript which contains the structure of a json record. Is it possible to create and write it as .json? Can anyone provide me with an example? I am suspecting that I need to use php but I cannot find a similar example.

From my javascript file called canvasJS.js :

     var delayInMilliseconds = 1000; //1 second
  setTimeout(function() {

    seq["canvases"] = allCanvases;
    var jarraySeq = [];
    jarraySeq.push(seq);


    obj["sequences"] = jarraySeq;


  }, delayInMilliseconds);

  console.log(obj);
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", "/json.php");
  xmlhttp.setRequestHeader("Content-Type", "application/json");
  xmlhttp.send(JSON.stringify(obj));

This is my json.php file -

 <?php
debug_to_console("test");
$json = file_get_contents('php://input');
file_put_contents('file.json', $json);

function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);

    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}


?>

but I am not able to create the file.json nor get an error in console. Any idea why?

Manwel
  • 1
  • 2
  • Does this answer your question? [Convert JS object to JSON string](https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – Nirav Joshi Dec 03 '19 at 08:45
  • not really I would like to know how to create a php call from javascript to pass the js object and save it in a new .json file – Manwel Dec 03 '19 at 08:48
  • you mean to save your json structured data into abc.json file in your local system or you want to pass the var as json object ?m – user6250770 Dec 03 '19 at 08:48

1 Answers1

0

This is how i would do it

javascript

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://localhost/json-writer.php");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({prop:"value"}))

php

$json = file_get_contents('php://input');
file_put_contents('file.json', $json);
Nathan Kolpa
  • 89
  • 1
  • 11
  • Hi I have tried your code and still didn't work...would you kindly check what I did wrong? I included the code in my question – Manwel Dec 03 '19 at 09:04