Laci Laci - 2 months ago 19
jQuery Question

Simple save to JSON file with JQuery

I've tried out all examples I could get my hands on, yet I can't simply save JSON data to a JSON file on my host. I want to start with a simple as possible save method so I have a place to start from.

Here's what I got:
Basically I have a button in my index.html which on click should save data to my general.json file (same location as index.html).

<button id="savebtn">Save</button>


With id selector in a myscript.js I do this:

$('#savebtn').click(function() {
var saveit = $('#calendar').fullCalendar( 'clientEvents');

var eventsholded = [];

$.each(saveit, function(index,value) {
var event = new Object();
event.id = value.id;
event.start = value.start;
event.end = value.end;
event.title = value.title;
event.allDay = value.allDay
eventsholded.push(event);
});
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'general.json',
data: JSON.stringify(eventsholded),
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
});


As you can see I want to store events from fullcalendar. That is not very relevant because it works fine till this point.
If I alert on screen JSON.stringify(eventsholded) you will see this:

[{"start":"2014-01-07T08:30:00.000Z","end":"2014-01-07T12:30:00.000Z","title":"Pumukli Pista","allDay":false},{"start":"2014-01-11T13:30:00.000Z","end":"2014-01-11T18:30:00.000Z","title":"Fanic Catalin","allDay":false}]


Now this is exactly what I want to save to server in simple, quick, maybe unsecure, but very simple way. Just so I can start to understand how this works, just to have that in my general.json file.

The
$.ajax
part does nothing in my above code. Not even alerting "Error". The rest of the code works as expected.

Security is not important now. I just want to learn how it works.

I will be grateful for any help or useful links that have complete examples. Thank you!

Answer

$.ajax alone will not save the json file, you need to direct the url property to a server-side script, i.e. http://your.host/save_json.php, that will create general.json and write your output on it. Something like:

PHP:

<?php
$myFile = "general.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_GET["data"];
fwrite($fh, $stringData);
fclose($fh)
?>

You'll also need to change the data property in your ajax call to data: {data: JSON.stringify(eventsholded)} to give the GET variable a proper name that can be retrieved from PHP:

JQUERY

$.ajax
    ({
        type: "GET",
        dataType : 'json',
        async: false,
        url: 'http://your.host/save_json.php',
        data: { data: JSON.stringify(eventsholded) },
        success: function () {alert("Thanks!"); },
        failure: function() {alert("Error!");}
    });