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":"sree@hmail.com","phone":"123456789"}
I have an existing JSON file named contact.json
{
"info": [
{
"name":"Noob Here",
"email":"myemail@server.com",
"phone":"123456"
},
{
"name":"Newbie There",
"email":"hisemail@server.com",
"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.
As far as i known the saving the data into local Json will not be possible by pure javascript or jquery.
If you want to save json in server side use server side programming like java or php otherwise use HTML5 for client side.
as suggested by Arun