It seems to me that the way you try to create your JSON is impractical, if not incorrect.
Here I show several possible ways to do it. For more ease it would be convenient to put all the data you want in a form
.
In the first option you will create a proper JSON (I would use that form preferably), since the second form creates you a JSON Array. It is also valid, but the JSON object will be found in the index 0
of the array.
var $frm = $("#myform");
/*1ª forma: Objeto JSON propiamente dicho*/
var json = formToJSON($frm);
console.log(json);
function formToJSON($form) {
var arrSerialize = $form.serializeArray();
var arrNew = {};
$.map(arrSerialize, function(n, i) {
arrNew[n['name']] = n['value'];
});
return arrNew;
}
/*2ª forma: Array JSON*/
var data = JSON.stringify($frm.serializeArray());
console.log(data);
/*3ª forma: Objeto JSON manual*/
var jsonManual =
'{"nombre":"' + $("#nombre").val() + '",' +
'"puntos":"' + $("#puntos").val() + '"}';
console.log(jsonManual);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input id="nombre" name="nombre" value="nombre test" />
<input id="puntos" name="puntos" value="10" />
</form>
As for PHP, keep in mind that the use of fopen
with w
places the pointer at the beginning of the file, rewriting it. If you want to continue adding content, you can use a
. For more details you can see here and in the PHP Manual there is a wider list of all the possibilities offered by fopen
.