Save form data in 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 stored data in the json file should be like this.

[ {"title":"some text","description":"some text","info":"some text","username":"some name"}, {"title":"some text","description":"some text","info":"some text","username":"some name"}, {"title":"some text","description":"some text","info":"some text","username":"some name"} ] 

I tried to do this using this code, but no data was saved in my "story.json file"

 $('form').submit(function() { $.ajax({ type: 'POST', dataType: 'json', url: 'story.json', data: $(this).serialize(), success: function(data) { alert(data.message); }, failure: function (data) { alert('Please try again'); } }); }); 

I want to save the data of this form in a local file. Please help me find the right way to do this. Thanks

+4
source share
3 answers

You need to send data to a simple php file ...

as url: 'story.php' In this php file, create "story.json" with fopen and save json

EDIT: if you want to use serialize() than use this type

 data:{'mydata':$(this).serialize()} 

and in php file

 parse_str($_POST['mydata'],$newarray) ; echo json_encode($newarray); 
+3
source

JavaScript cannot save a file unless it is a FireFox plugin.

What you do is submit the form (submit it to the web server) and then allow the server side script.

Serialize does not turn form values ​​into a JSON string:

http://api.jquery.com/serialize/

And when you use $ .post, you should return false in $ ('form'). submit (function () or the browser will send you a form.

Form submission occurs when you click the button, and the whole page runs for a while, and then you get a new page.

Ajax ($ .post, $ .get, $ .getJson ...) is when you send information to the server without refreshing the page. Google Maps is a great example.

+2
source

Calling the serialize method on a jQuery form object does not return a JSON representation of its data. It returns a representation of its data. As mentioned above, you will need to use the server side of the script to interpret (and manipulate) the data sent and save it in a file as JSON.

0
source

Source: https://habr.com/ru/post/1442584/


All Articles