Saving data to local json file using jquery

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.

+4
source share
1 answer

As far as I know, saving data to local Json will not be possible using pure javascript or jquery. If you want to keep json on the server side, use server-side programming, such as java or php, otherwise use HTML5 for the client side.

as suggested by Arun

+4
source

All Articles