2

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);
?>
1
  • $map=json_decode($_POST['json_string']); you didn't post any json_string, nor any JSON to be decoded. type: 'POST' with default settings will send an application/x-www-form-urlencoded POST request with the key->value pairs of your object. Commented Sep 21, 2012 at 23:54

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer! However, still not working. I replaced the AJAX request and the PHP code (using var_export). I get a NULL in the file.
Do a quick die(var_dump($_POST)); to see what's inside and act accordingly.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.