I'm having some trouble writing to a JSON file using ajax/jQuery along with PHP. The code I have currently is:
jQuery
var object = {
name: 'John',
occupation: 'Lawyer'
}
$(".testing-php").click(function () {
$.ajax({
type: 'POST',
data: {params:object},
url: 'details.php',
success: function (data) {
console.log(object);
alert('success');
},
error: function () {
alert('error');
}
});
This part seems to be working correctly as the console.log statement correctly displays - {"name":"John","occupation":"Lawyer"}
My PHP file is currently like this:
<?php
var_dump($_POST);
if (isset($_POST['params']) && strlen($_POST['params'])) {
$params = $_POST['params'];
$jsonObject = json_encode($params);
if (is_writable('js/details.json')) {
file_put_contents('js/details.json', $jsonObject);
echo "success";
} else {
echo "file is not writable, check permissions";
}
} else {
echo "invalid params";
}
?>
Finally, the current JSON file looks like this:
{
"name": "Neil",
"occupation": "web developer"
}
Update
This is the information which the var_dump($_POST) displays. Along with the message .invalid params'.
array(1) {
["params"]=>
array(2) {
["name"]=>
string(4) "John"
["occupation"]=>
string(6) "Lawyer"
}
}
invalid params
The AJAX request parameters are on two different rows and are displayed as
params[name]:"John"
params[occupation]:"Lawyer"
I am simply hardcoding values at the moment until I get the process working. Can anyone tell me what I am doing wrong here as the JSON file isn't being written to?
Many thanks
processData: false,underdata: params,