0

I'm a noob struggling with something relativly simple (or so I believe). Writing an json or more precisly geojson object to a file with jquery ajax. My approach looks like this so far

    $.ajax({
        type: 'POST',
        url: "data/markers.geojson",   //url of receiver file on server
        data: data,                    //geojson data
        dataType: "json"               
      });

Looks fine, I think, but unfortunately the markers.geojson file remains completely empty. If I log the content of the data variable to the console right before the '$.ajax' it's all there. And the network console shows that bytes are transfered.

Now after searching a lot I noticed that everybody else seems to be sending json data not to a .json file but a .php file. Unfortunately they all seem to do other stuff on the php side or nobody deems it necessary to post the method to save the received json to a file on the server.

Alas, I'm a beginner and could really need some help here - how should the .php file look to just save the json to a file?

EDIT This answer in the other question solved the problem:

<?php
$myFile = "testFile.txt";
$phpObj = json_decode($_POST['json']);
file_put_contents($myFile,$phpObj);
echo '{ "success": true }';
?>
  • just don't forget to enable php in your apache ;-) And again thanks to the patient @ADyson to walk a beginner through this.
Merion
  • 195
  • 2
  • 10
  • 1
    https://stackoverflow.com/questions/16931804/recording-a-json-post-to-file-using-php looks like almost an exact duplicate of your question – ADyson May 04 '20 at 21:04
  • I tried the top answers, but it did not do anything unfortunately. The json file still sits at 0 byte – Merion May 04 '20 at 21:43
  • "did not do anything" isn't enough information for us to be able to debug your problem. See https://stackoverflow.com/help/minimal-reproducible-example – ADyson May 04 '20 at 21:49
  • Sorry, So I changed the 'url:' line to 'url: "data/saveJSON.php",' where data is the target directory and saveJSON.php the php file I created there with the content of user complistic's anwer. Namely ''. After reloading my page and hitting the save button, I see bytes tranfered and also a byte size in the firefox network console. The markers.geojson file is still empty though. – Merion May 04 '20 at 21:55
  • Do some debugging in the PHP, then. Check the content of `$jsonString` for one thing, to see what's in there. `var_dump($jsonString);` will dump that variable to the response (so in the firefox network console you'd see it in the "Response" tab of the call to saveJSON.php). Also, have you got error logging switched on in PHP, and errors and warnings enabled? That would allow you to see if there are any errors e.g. related to file permissions or something when saving the file. https://stackify.com/php-error-logs-guide/ has a guide to configuring that. – ADyson May 04 '20 at 22:10
  • P.S. as an aside...this bit: `echo '{ "success": true }';` ...don't do it. Don't make JSON by hand like that. PHP has the `json_encode` function for a reason - use it. – ADyson May 04 '20 at 22:11
  • Thanks for your patience. So I enabled error logging and in the network response tab I just get the content of the saveJSON.php file shown. But in the params tab under form data the json content is all there. – Merion May 04 '20 at 22:46
  • "I just get the content of the saveJSON.php file shown"...you mean it prints the actual PHP code in the response? If so, that means you haven't enabled PHP in your server properly. Start here as a reference: https://stackoverflow.com/questions/5121495/php-code-is-not-being-executed-instead-code-shows-on-the-page/19387922 Or this one: https://stackoverflow.com/questions/12142172/apache-shows-php-code-instead-of-executing or several others you can find easily online – ADyson May 04 '20 at 22:48
  • Oops, well, now it's enabled and surprise, suddenly it works! Thank you so much, you're my hero for today! If you value onsite reputation, please add an official answer an I happily accept and upvote it. – Merion May 04 '20 at 23:08
  • You can't upvote, you don't have enough reputation yet! See https://stackoverflow.com/help/privileges. But thanks. No I just pointed you in the right direction really - your question is a duplicate of the one I first mentioned. No new answer is needed really. You implemented it all yourself, based on the existing answer in that other question. (P.S. you are allowed to answer your _own_ question, if you wish). – ADyson May 04 '20 at 23:18

1 Answers1

1

Try this example:

<?php
//error_reporting(E_ALL);
//var_dump($_SERVER);
$post_data = $_POST['data'];
if (!empty($post_data)) {
    $dir = 'YOUR-SERVER-DIRECTORY/files';
    $file = uniqid().getmypid();
    $filename = $dir.$file.'.txt';
    $handle = fopen($filename, "w");
    fwrite($handle, $post_data);
    fclose($handle);
    echo $file;
}
?>

You PHP file mast have name: index.php in to dir: /data/markers.geojson/

and you code:

 $.ajax({
        type: 'POST',
        url: "https://www.example.com/data/markers.geojson/",   //url of receiver file on server
        data: data,                    //geojson data
        dataType: "json"               
      });
Sergey Kozlov
  • 452
  • 5
  • 17
  • Why did you put `dataType: "json"`, when `echo $file;` just returns plain text? There's no point telling the client to expect JSON in the response, when you know the server is not returning JSON. – ADyson May 04 '20 at 21:34
  • Sorry, if I'm being dense here, but I did not even expect to need to use php and am a complete newbie. So, just to clarify: does ''$dir = 'YOUR-SERVER-DIRECTORY/files';''' need the full webadress? Or just a relative path? And what if they're in the same directory? And do I understand correctly that I declare the file extension in `$filename = $dir.$file.'.txt';´ and the actual file name in '$handle = fopen($filename, "w");'? Btw. markers.geojson is the json file everything should be stored in, /data is the directory. – Merion May 04 '20 at 21:48
  • @Merion `does ''$dir = 'YOUR-SERVER-DIRECTORY/files';''' need the full webadress?` . In this example `$dir` should be a path on the server's disk, to where you want to save the file. Nothing to do with a web URL. – ADyson May 04 '20 at 22:12
  • okay, so basically a "/data" should suffice. – Merion May 04 '20 at 22:14
  • @Merion `do I understand correctly that I declare the file extension in $filename = $dir.$file.'.txt'; and the actual file name in '$handle = fopen($filename, "w");'? ` ...nope, the full filename is in $filename - you can see clearly the ".txt" extension is appended there. The second line creates a _file handle_ - i.e. an object which acts as a reference to that file while it's open. Usually simpler to use file_put_contents though, as per other examples you've seen. – ADyson May 04 '20 at 22:14