graphmeter
graphmeter

Reputation: 1125

Writing data to file using PHP and AJAX not working

I am trying to save json data to a file using AJAX and PHP but the resulting file is empty. Why is it not working?

Here is the HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>

var dataset = {"value1": 2, "value2": 1000};

$.ajax({
   url: 'save.php',
   type: 'POST',
   data: dataset,
   success: function() {
      alert('Success');
   }
});

</script>
</body>
</html>

save.php:

<?php 
$map=json_decode($_POST['json_string']);
$file = "test.json"; 
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $map);
fclose($fh);
?>

Upvotes: 2

Views: 1670

Answers (2)

Teena Thomas
Teena Thomas

Reputation: 5239

change this line $map=json_decode($_POST['json_string']); to $map=json_decode($_POST['dataset']);

Upvotes: 0

Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 10467

You're using wrong POST variable name. Firstly, send your AJAX request with:

data: { 
    json: dataset
    },

And then use:

$map = $_POST['json'];

Don't decode it since you want to save JSON string, not an array. If you want PHP representation, better use var_export():

$map = var_export(json_decode($_POST['json'], true), true);

Upvotes: 2

Related Questions