I have a basic form with some input fields. I want to save the form data into a json file on submitting the form.
The format of the data from form is:
{"name":"Sree","email":"[email protected]","phone":"123456789"}
I have an existing JSON file named contact.json
{
"info": [
{
"name":"Noob Here",
"email":"[email protected]",
"phone":"123456"
},
{
"name":"Newbie There",
"email":"[email protected]",
"phone":"589433"
}
]
}
This is the function that i use to make data as json:
function submit_form(){
var data=(JSON.stringify($('form').serializeObject()));
return false;
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
I have tried inserting this code into the submit_form function
$.ajax({
type: 'POST',
dataType: 'json',
url: 'contact.json',
data: data,
success: function(data) {
alert(data.message);
},
failure: function (data) {
alert('Please try again');
}
});
I'm new with json and have no idea how to fix this.