moein rahimi moein rahimi - 2 months ago 11
Ajax Question

how to send ajax via jquery in getcontenttools library

hi i'm using https://github.com/getmeuk/ContentTools library in my project, in the docs uses plain js to send ajax request, i want to send data using jquery,
but i have no idea how to that.

this is the code for sending ajax in plain javascript :

// Send the update content to the server to be saved
onStateChange = function(ev) {
// Check if the request is finished
if (ev.target.readyState == 4) {
editor.busy(false);
if (ev.target.status == '200') {
// Save was successful, notify the user with a flash
if (!passive) {
new ContentTools.FlashUI('ok');
}
} else {
// Save failed, notify the user with a flash
new ContentTools.FlashUI('no');
}
}
};

xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '/x/save-page');
xhr.send(payload);

Answer

Using JQuery this section of the tutorial could be rewritten like so:

// Collect the contents of each region into an object we can send to the 
// server.
var payload = {'__page__': window.location.pathname};
for (var name in regions) {
    payload[name] = regions[name];
}

// Send the updated content to the server to be saved
var req = $.ajax({
    method: 'POST',
    url: '/x/save-page',
    data: payload
    });

req.done(function() {
    // Save was successful, notify the user with a flash
    new ContentTools.FlashUI('ok');
});

req.fail(function() {
    // Save failed, notify the user with a flash
    new ContentTools.FlashUI('no');
});

req.always(function() {
    // Make sure the editor is no longer set in a busy state
    ContentTools.EditorApp.get().busy(false);
});
Comments