Reputation: 31
I need to write a json object to a .json file using javascript and php. The json object seems to be storing the values correctly, but the php file doesn't seem to run so nothing happens.
Thanks.
my javascript function, which is called on a button click:
function save_crime()
{
//json object, v1, v2, v3 etc are variables whose values are set in a different function
var jsonObject = { "crime" : { "violence" : { "violence1" : v1,
"violence2" : v2,
"violence3" : v3
},
"burglary" : { "burglary1" : b1,
"burglary2" : b2
},
"robbery" : { "robbery1" : r1,
"robbery2" : r2
},
"criminal" : { "criminal1" : c1,
"criminal2" : c2,
"criminal3" : c3
}
}
}
//jQuery to post json object to json.php for writing to json file
$.ajax({
type : "POST",
url : 'json.php',
dataType : 'json',
data : {
json : JSON.stringify(jsonObject)
}
});
}
php file for writing to .json file:
<?php
$json = $_POST['json'];
$info = json_encode($json);
$file = "crimes.json";
$handle = fopen($file, 'w');
fwrite($handle, $info);
fclose($handle);
?>
Upvotes: 3
Views: 5176
Reputation: 57650
You are writing the JSON string to a file, you dont need to decode as its a string already from JS part (JSON.stringify(jsonObject)
).
Just write it directly.
file_put_contents("crimes.json", $_POST['json']);
Its better to get a response from server so that you know the action is performed properly. Use the $.post
shorthand instead of $.ajax
.
$.post(
'json.php',
{
json : JSON.stringify(jsonObject)
},
function (data, textStatus, jqXHR){
}
);
Upvotes: 1