Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ace editor - save/send session on server via POST

I write online webpage editor and I would like save current view/work on server, for restore in future. I also want do multiple tabs.

I know, that is editor.getSession() and editor.setSession().

JS:

var editor = ace.edit("description");
editor.session.setMode("ace/mode/javascript");
editor.setTheme("ace/theme/tomorrow");
editor.setShowPrintMargin(false);
editor.setOptions({
    enableBasicAutocompletion: true,
    enableSnippets: true
});

Now I try save session via jQuery $.data() to element:

$('#tab1').data('sesi',editor.getSession()); //save session
editor.setSession($('#tab2').data('sesi')); //restore other session

But this code not working. When I try console.log(editor.session); I see a lot of code in console.

I tried send session to server via POST data, but in network console I see only code from editor and nothing more...

$.ajax({
    type: "POST",
    url: "aaaaa.php",
    cache: false,
    timeout: 10000,
    data: "session="+ editor.session
});

How to save session to variable or to server?

like image 347
Peter Avatar asked Jan 31 '15 23:01

Peter


1 Answers

to save session to server you need to convert it to plain object which can be passed to json.Stringify. session="+ editor.session in your example simply calls session.toString which is same as session.getValue

var filterHistory = function(deltas){ 
    return deltas.filter(function (d) {
        return d.group != "fold";
    });
}

sessionToJSON = function(session) {
    return {
        selection: session.selection.toJSON(),
        value: session.getValue(),
        history: {
            undo: session.$undoManager.$undoStack.map(filterHistory),
            redo: session.$undoManager.$redoStack.map(filterHistory)
        },
        scrollTop: session.getScrollTop(),
        scrollLeft: session.getScrollLeft(),
        options: session.getOptions()
    }
}

sessionFromJSON = function(data) {
    var session = require("ace/ace").createEditSession(data.value);
    session.$undoManager.$doc = session; // workaround for a bug in ace
    session.setOptions(data.options);
    session.$undoManager.$undoStack = data.history.undo;
    session.$undoManager.$redoStack = data.history.redo;
    session.selection.fromJSON(data.selection);
    session.setScrollTop(data.scrollTop);
    session.setScrollLeft(data.scrollLeft);
    return session;
};

now to get state of the session do

var session = editor.session
var sessionData = sessionToJSON(session)
$.ajax({
    type: "POST",
    url: "aaaaa.php",
    cache: false,
    timeout: 10000,
    data: JSON.stringify(sessionData)
});

and to restore it from the server

var session = sessionFromJSON(JSON.parse(ajaxResponse))
editor.setSession(session)
like image 76
a user Avatar answered Oct 23 '22 02:10

a user