/**
* @type {Element}
*/
var saveButton = document.getElementById('save');
/**
* Stores array of all editable fields on the page.
* @type {NodeList}
*/
var editableFields = document.querySelectorAll('[data-editable-text-id]');
/**
* Stores the original inner HTML for each editable field on the page.
* @type {{}}
*/
var editableFieldsOriginalInnerHTML = {}
/**
* Stores the editable fields whose innerHTML has been changed.
* @type {{}}
*/
var editableFieldsChanged = {}
/**
* Retrieves and stores inner HTML from all editable fields.
*/
function retrieveEditableFieldsInnerHTML() {
for (var i = 0; i < editableFields.length; i++) {
var field = editableFields[i],
id = field.dataset.editableTextId;
// store original html for current editable field
editableFieldsOriginalInnerHTML[id] = field.innerHTML;
}
}
retrieveEditableFieldsInnerHTML();
//console.dir(editableFieldsOriginalInnerHTML)
var editableParagraph = editableFields[0];
//console.dir(editableParagraph);
//console.dir(editableFieldsOriginalInnerHTML);
saveButton.addEventListener('click', function(e) {
//console.dir(editableFields)
//console.dir(editableFieldsOriginalInnerHTML)
for (var i = 0; i < editableFields.length; i++) {
var field = editableFields[i],
id = field.dataset.editableTextId;
/**
* match the current inner html of the editable field element inner html against the
* corresponding original inner html value for changes
*/
if (field.innerHTML !== editableFieldsOriginalInnerHTML[id]) {
/**
* collect all editable fields that have changed and their corresponding
* data-editable-text-id and innerHTML
*/
editableFieldsChanged[id] = field.innerHTML
}
}
console.dir(editableFieldsChanged);
// get current page name being edited
var pathArray = window.location.pathname.split( '/' );
var currentPage = pathArray[5];
/**
* ajax request to send edited fields and store them in the database which will be used
* on next page reload.
*/
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('ajax success');
//window.location.replace('http://localhost/pageEdits/index.php');
// return to admin console
window.location.replace('/../index.php/content-manager');
} else {
console.log('ajax failed');
}
}
}
// open the connection POST the data retrieved
xhr.open('POST', encodeURI('index.php/content-manager/save/' + currentPage), true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(editableFieldsChanged));
}, false);