0

I am trying to build a web app where users can use OpenLayers to draw features and then save them either as a download or write to a file on the server which I can collect when I need it. I am happy with the OL3 bit so far. From reading around it seems AJAX is the way to do this so I have managed to included a button in my HMTL which runs a function that runs a php file to create a new file.I was pretty happy that I managed to get an empty text file as a start. So how do I get that file to contain the JSON information? I assume I need to send it from the JS world to PHP somehow? I have seen a answer using jquery which sends data though post but I can't figure out how to run that script on my page.

The Function

function loadXMLDoc()
{
var xmlhttp=new XMLHttpRequest();

xmlhttp.open("GET","run.php",true);
xmlhttp.send();
}
</script>

The button

<button type="button" onclick="loadXMLDoc()">do something</button>
The PHP file (run.php)

<?php
$myfile = fopen("store/anothernewfile.geojson", "w") or die("Unable to open     file!");
$txt = ['lyr_site'];
fwrite($myfile, $txt);
fclose($myfile);
?>
Community
  • 1
  • 1
Sethinacan
  • 103
  • 2

1 Answers1

0

Try sending a POST request that contains your JSON object to your PHP file:

Client-side Javascript:

function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open('POST', 'run.php', true);
  xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xmlhttp.send(JSON.stringify({ foo: 'Hey', bar: true}));
}

Server-side PHP:

<?php
  $request_body = file_get_contents("php://input");
  $myfile = fopen("store/anothernewfile.geojson", "w") or die("Unable to open     file!");
  fwrite($myfile, $request_body);
  fclose($myfile);
?>
Mario Pabon
  • 585
  • 3
  • 8
  • Your code works and I am nearly there. but the contents of the GEOJson file have loads of extra slashes `function loadXMLDoc() { var geoJSON = new ol.format.GeoJSON(); var jsondata = geoJSON.writeFeatures(lyr_site.getSource().getFeatures()); var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', 'run.php', true); xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xmlhttp.send(JSON.stringify(jsondata));` – Sethinacan Sep 10 '15 at 07:41
  • The extra slashes seems to be because of the `.stringify` so I removed that and I get a file that opens and has attributes but no spatial extents even though the file is full of coordinates. `xmlhttp.send(jsondata);` – Sethinacan Sep 10 '15 at 07:55
  • The file is mostly fine but is missing this the following line, if I add it manually it works fine. `"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },` – Sethinacan Sep 10 '15 at 08:22