I have a basic form with some input fields. I want to save form data to json file when submitting form.
The format of the data from the form:
{"name":"Sree","email":" sree@hmail.com ","phone":"123456789"}
I have an existing JSON file called 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 I use to create 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 tried to insert 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 am new to json and have no idea how to fix this.
source share