Saving and loading words from words table now works. Need to make words delete when dictionary is deleted.

This commit is contained in:
Robbie Antenesse 2016-06-14 18:16:41 -06:00
parent 7e9c14a7c2
commit 8109bdac69
3 changed files with 296 additions and 186 deletions

View File

@ -69,6 +69,7 @@ function AddWord() {
} }
} else { } else {
currentDictionary.words.push({name: word, pronunciation: pronunciation, partOfSpeech: ((partOfSpeech.length > 0) ? partOfSpeech : " "), simpleDefinition: simpleDefinition, longDefinition: longDefinition, wordId: currentDictionary.nextWordId++}); currentDictionary.words.push({name: word, pronunciation: pronunciation, partOfSpeech: ((partOfSpeech.length > 0) ? partOfSpeech : " "), simpleDefinition: simpleDefinition, longDefinition: longDefinition, wordId: currentDictionary.nextWordId++});
SaveAndUpdateWords("new", wordIndex);
FocusAfterAddingNewWord(); FocusAfterAddingNewWord();
NewWordNotification(word); NewWordNotification(word);
SaveAndUpdateDictionary(false); SaveAndUpdateDictionary(false);
@ -165,7 +166,8 @@ function UpdateWord(wordIndex, word, pronunciation, partOfSpeech, simpleDefiniti
currentDictionary.words[wordIndex].simpleDefinition = simpleDefinition; currentDictionary.words[wordIndex].simpleDefinition = simpleDefinition;
currentDictionary.words[wordIndex].longDefinition = longDefinition; currentDictionary.words[wordIndex].longDefinition = longDefinition;
SaveAndUpdateDictionary(); SaveAndUpdateWords("update", wordIndex);
// SaveAndUpdateDictionary();
window.scroll(savedScroll.x, savedScroll.y); window.scroll(savedScroll.x, savedScroll.y);
@ -408,6 +410,44 @@ function ResetDictionaryToDefault() {
currentDictionary = JSON.parse(defaultDictionaryJSON); currentDictionary = JSON.parse(defaultDictionaryJSON);
} }
function SaveAndUpdateWords(action, wordIndex) {
var dataToSend = "";
if (action == "all") {
// For dictionaries not already in the db. Send all the words to database.
dataToSend = JSON.stringify(currentDictionary.words);
} else if (action == "update") {
// Only send the specified word to update.
dataToSend = JSON.stringify(currentDictionary.words[wordIndex]);
} else if (action == "new") {
// Send the last word pushed to the words array before it's sorted.
dataToSend = JSON.stringify(currentDictionary.words[currentDictionary.words.length - 1]);
}
var sendWords = new XMLHttpRequest();
sendWords.open('POST', "php/ajax_dictionarymanagement.php?action=word" + action);
sendWords.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
sendWords.onreadystatechange = function() {
if (sendWords.readyState == 4 && sendWords.status == 200) {
if (sendWords.responseText == "sent successfully") {
console.log(sendWords.responseText);
LoadUserDictionaries();
ProcessLoad();
} else if (isNaN(parseInt(sendWords.responseText))) {
console.log(sendWords.responseText);
} else { // It will only be a number if it is a new dictionary.
currentDictionary.externalID = parseInt(sendWords.responseText);
LoadUserDictionaries();
ProcessLoad();
console.log("saved successfully");
}
return true;
} else {
return false;
}
}
sendWords.send(dataToSend);
}
function SaveAndUpdateDictionary(keepFormContents) { function SaveAndUpdateDictionary(keepFormContents) {
if (!currentDictionary.settings.sortByEquivalent) { if (!currentDictionary.settings.sortByEquivalent) {
currentDictionary.words.sort(dynamicSort(['name', 'partOfSpeech'])); currentDictionary.words.sort(dynamicSort(['name', 'partOfSpeech']));
@ -422,28 +462,26 @@ function SaveAndUpdateDictionary(keepFormContents) {
CloseUpdateConflictArea('newWordButtonArea', 'updateConflict'); CloseUpdateConflictArea('newWordButtonArea', 'updateConflict');
} }
function SaveDictionary(sendToDatabase, sendWords) { function SaveDictionary(sendToDatabase) {
localStorage.setItem('dictionary', JSON.stringify(currentDictionary)); localStorage.setItem('dictionary', JSON.stringify(currentDictionary));
//Always save local copy of current dictionary, but if logged in also send to database. //Always save local copy of current dictionary, but if logged in also send to database.
if (sendToDatabase) { if (sendToDatabase) {
sendWords = (typeof sendWords !== 'undefined') ? sendWords : false; SendDictionary();
SendDictionary(sendWords);
} }
SavePreviousDictionary(); SavePreviousDictionary();
} }
function SendDictionary(sendWords) { function SendDictionary() {
sendWords = (typeof sendWords !== 'undefined') ? sendWords : false;
var action = ""; var action = "";
var postString = ""; var postString = "";
if (currentDictionary.externalID > 0) { if (currentDictionary.externalID > 0) {
action = "update"; action = "update";
postString = DataToSend(sendWords); postString = DataToSend(false);
} else { } else {
action = "new"; action = "new";
postString = DataToSend(true, true); postString = DataToSend(true);
} }
var sendDictionary = new XMLHttpRequest(); var sendDictionary = new XMLHttpRequest();
@ -459,6 +497,7 @@ function SendDictionary(sendWords) {
console.log(sendDictionary.responseText); console.log(sendDictionary.responseText);
} else { // It will only be a number if it is a new dictionary. } else { // It will only be a number if it is a new dictionary.
currentDictionary.externalID = parseInt(sendDictionary.responseText); currentDictionary.externalID = parseInt(sendDictionary.responseText);
SaveAndUpdateWords("all");
LoadUserDictionaries(); LoadUserDictionaries();
ProcessLoad(); ProcessLoad();
console.log("saved successfully"); console.log("saved successfully");
@ -471,7 +510,7 @@ function SendDictionary(sendWords) {
sendDictionary.send(postString); sendDictionary.send(postString);
} }
function DataToSend(doSendWords, sendAll) { function DataToSend(sendAll) {
sendAll = (typeof sendAll !== 'undefined' && sendAll != null) ? sendAll : false; sendAll = (typeof sendAll !== 'undefined' && sendAll != null) ? sendAll : false;
var data = ""; var data = "";
if (currentDictionary.externalID == 0) { if (currentDictionary.externalID == 0) {
@ -485,9 +524,6 @@ function DataToSend(doSendWords, sendAll) {
if (sendAll || currentDictionary.description != previousDictionary.description) { if (sendAll || currentDictionary.description != previousDictionary.description) {
data += ((data=="") ? "" : "&") + "description=" + encodeURIComponent(currentDictionary.description); data += ((data=="") ? "" : "&") + "description=" + encodeURIComponent(currentDictionary.description);
} }
if (sendAll || doSendWords) {
data += ((data=="") ? "" : "&") + "words=" + encodeURIComponent(JSON.stringify(currentDictionary.words));
}
if (sendAll || currentDictionary.nextWordId != previousDictionary.nextWordId) { if (sendAll || currentDictionary.nextWordId != previousDictionary.nextWordId) {
data += ((data=="") ? "" : "&") + "nextwordid=" + currentDictionary.nextWordId; data += ((data=="") ? "" : "&") + "nextwordid=" + currentDictionary.nextWordId;
} }

View File

@ -218,8 +218,8 @@ function dynamicSort(propertiesArray) {
dir = -1; dir = -1;
o=o.substring(1); o=o.substring(1);
} }
if (removeDiacritics(a[o]) > removeDiacritics(b[o])) return dir; if (removeDiacritics(a[o]).toLowerCase() > removeDiacritics(b[o]).toLowerCase()) return dir;
if (removeDiacritics(a[o]) < removeDiacritics(b[o])) return -(dir); if (removeDiacritics(a[o]).toLowerCase() < removeDiacritics(b[o]).toLowerCase()) return -(dir);
return 0; return 0;
}) })
.reduce(function firstNonZeroValue (p,n) { .reduce(function firstNonZeroValue (p,n) {

View File

@ -4,28 +4,39 @@ require_once('config.php');
require_once(SITE_LOCATION . '/php/functions.php'); require_once(SITE_LOCATION . '/php/functions.php');
session_start(); session_start();
if ($_SESSION['user'] > 0) {
if ($_GET['action'] == 'getall') { if ($_GET['action'] == 'getall') {
Get_Dictionaries(true); Get_Dictionaries(true);
} }
elseif ($_GET['action'] == 'load') { elseif ($_GET['action'] == 'load') {
Load_Current_Dictionary(); Load_Current_Dictionary();
} }
elseif ($_GET['action'] == 'new') { elseif ($_GET['action'] == 'new') {
Save_Current_DictionaryAsNew(); Save_Current_DictionaryAsNew();
} }
elseif ($_GET['action'] == 'update') { elseif ($_GET['action'] == 'update') {
Update_Current_Dictionary(); Update_Current_Dictionary();
} }
elseif ($_GET['action'] == 'switch') { elseif ($_GET['action'] == 'wordall') {
Save_New_Word(true);
}
elseif ($_GET['action'] == 'wordnew') {
Save_New_Word(false);
}
elseif ($_GET['action'] == 'wordupdate') {
Update_Word();
}
elseif ($_GET['action'] == 'switch') {
Switch_Current_Dictionary($_POST['newdictionaryid'], true); Switch_Current_Dictionary($_POST['newdictionaryid'], true);
} }
elseif ($_GET['action'] == 'delete') { elseif ($_GET['action'] == 'delete') {
Delete_Current_Dictionary(); Delete_Current_Dictionary();
}
} else {
echo "not signed in";
} }
function Get_Dictionaries($return_list = true) { function Get_Dictionaries($return_list = true) {
if ($_SESSION['user'] > 0) {
$query = "SELECT `id`, `name` FROM `dictionaries` WHERE `user`=" . $_SESSION['user'] . " ORDER BY `name` ASC;"; $query = "SELECT `id`, `name` FROM `dictionaries` WHERE `user`=" . $_SESSION['user'] . " ORDER BY `name` ASC;";
$dictionaries = query($query); $dictionaries = query($query);
@ -48,14 +59,10 @@ function Get_Dictionaries($return_list = true) {
} else { } else {
echo "could not load"; echo "could not load";
} }
} else {
echo "not signed in";
}
return false; return false;
} }
function Load_Current_Dictionary() { function Load_Current_Dictionary() {
if ($_SESSION['user'] > 0) {
$query = "SELECT `d`.`id`, `d`.`name`, `d`.`description`, `u`.`public_name`, `d`.`words`, `d`.`next_word_id`, `d`.`allow_duplicates`, `d`.`case_sensitive`, `d`.`parts_of_speech`, `d`.`sort_by_equivalent`, `d`.`is_complete`, `d`.`is_public` "; $query = "SELECT `d`.`id`, `d`.`name`, `d`.`description`, `u`.`public_name`, `d`.`words`, `d`.`next_word_id`, `d`.`allow_duplicates`, `d`.`case_sensitive`, `d`.`parts_of_speech`, `d`.`sort_by_equivalent`, `d`.`is_complete`, `d`.`is_public` ";
$query .= "FROM `dictionaries` AS `d` LEFT JOIN `users` AS `u` ON `user`=`u`.`id` WHERE `d`.`id`=`u`.`current_dictionary` AND `user`=" . $_SESSION['user'] . ";"; $query .= "FROM `dictionaries` AS `d` LEFT JOIN `users` AS `u` ON `user`=`u`.`id` WHERE `d`.`id`=`u`.`current_dictionary` AND `user`=" . $_SESSION['user'] . ";";
$dictionary = query($query); $dictionary = query($query);
@ -68,7 +75,7 @@ function Load_Current_Dictionary() {
$json = '{"name":"' . $dict['name'] . '",'; $json = '{"name":"' . $dict['name'] . '",';
$json .= '"description":"' . $dict['description'] . '",'; $json .= '"description":"' . $dict['description'] . '",';
$json .= '"createdBy":"' . $dict['public_name'] . '",'; $json .= '"createdBy":"' . $dict['public_name'] . '",';
$json .= '"words":' . $dict['words'] . ','; $json .= '"words":[' . Get_Dictionary_Words($_SESSION['dictionary']) . '],';
$json .= '"nextWordId":' . $dict['next_word_id'] . ','; $json .= '"nextWordId":' . $dict['next_word_id'] . ',';
$json .= '"settings":{'; $json .= '"settings":{';
$json .= '"allowDuplicates":' . (($dict['allow_duplicates'] == 1) ? 'true' : 'false') . ','; $json .= '"allowDuplicates":' . (($dict['allow_duplicates'] == 1) ? 'true' : 'false') . ',';
@ -90,21 +97,47 @@ function Load_Current_Dictionary() {
} else { } else {
echo "could not load"; echo "could not load";
} }
} else {
echo "not logged in";
}
return false; return false;
} }
function Get_Dictionary_Words($dictionary) {
$query = "SELECT `w`.`word_id`, `w`.`name`, `w`.`pronunciation`, `w`.`part_of_speech`, `w`.`simple_definition`, `w`.`long_definition` ";
$query .= "FROM `words` AS `w` LEFT JOIN `dictionaries` AS `d` ON `w`.`dictionary`=`d`.`id` WHERE `w`.`dictionary`=" . $dictionary . " ";
$query .= "ORDER BY IF(`d`.`sort_by_equivalent`, `w`.`simple_definition`, `w`.`name`) COLLATE utf8_unicode_ci;";
$words = query($query);
$results = "";
$processed = 0;
if ($words) {
if (num_rows($words) > 0) {
while ($word = fetch($words)) {
$results .= '{"name":"' . $word['name'] . '",';
$results .= '"pronunciation":"' . $word['pronunciation'] . '",';
$results .= '"partOfSpeech":"' . $word['part_of_speech'] . '",';
$results .= '"simpleDefinition":"' . $word['simple_definition'] . '",';
$results .= '"longDefinition":"' . $word['long_definition'] . '",';
$results .= '"wordId":' . $word['word_id'] . '}';
// If it's the last one, then don't add a comma.
if (++$processed < num_rows($words)) {
$results .= ",";
}
}
}
}
return $results;
}
function Save_Current_DictionaryAsNew() { function Save_Current_DictionaryAsNew() {
if ($_SESSION['user'] > 0) {
$dbconnection = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD); $dbconnection = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD);
$dbconnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbconnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbconnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbconnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $dbconnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$query = "INSERT INTO `dictionaries`(`user`, `name`, `description`, `words`, `next_word_id`, `allow_duplicates`, `case_sensitive`, `parts_of_speech`, `sort_by_equivalent`, `is_complete`, `is_public`) "; $query = "INSERT INTO `dictionaries`(`user`, `name`, `description`, `next_word_id`, `allow_duplicates`, `case_sensitive`, `parts_of_speech`, `sort_by_equivalent`, `is_complete`, `is_public`) ";
$query .= "VALUES (" . $_SESSION['user'] . ",'" . $_POST['name'] . "','" . $_POST['description'] . "','" . $_POST['words'] . "'," . $_POST['nextwordid'] . "," . $_POST['allowduplicates'] . "," . $_POST['casesensitive'] . ",'" . $_POST['partsofspeech'] . "'," . $_POST['sortbyequivalent'] . "," . $_POST['iscomplete'] . "," . $_POST['ispublic'] . ")"; $query .= "VALUES (" . $_SESSION['user'] . ",'" . $_POST['name'] . "','" . $_POST['description'] . "'," . $_POST['nextwordid'] . "," . $_POST['allowduplicates'] . "," . $_POST['casesensitive'] . ",'" . $_POST['partsofspeech'] . "'," . $_POST['sortbyequivalent'] . "," . $_POST['iscomplete'] . "," . $_POST['ispublic'] . ")";
try { try {
$update = $dbconnection->prepare($query); $update = $dbconnection->prepare($query);
@ -119,14 +152,10 @@ function Save_Current_DictionaryAsNew() {
$errorMessage = $dbconnection->errorInfo(); $errorMessage = $dbconnection->errorInfo();
echo "could not update:\n" . $errorMessage[2] . "\n" . $query; echo "could not update:\n" . $errorMessage[2] . "\n" . $query;
} }
} else {
echo "not logged in";
}
return false; return false;
} }
function Update_Current_Dictionary() { function Update_Current_Dictionary() {
if ($_SESSION['user'] > 0) {
if (isset($_SESSION['dictionary'])) { if (isset($_SESSION['dictionary'])) {
$query = "UPDATE `dictionaries` SET "; $query = "UPDATE `dictionaries` SET ";
@ -136,9 +165,6 @@ function Update_Current_Dictionary() {
if (isset($_POST['description'])) { if (isset($_POST['description'])) {
$query .= "`description`='" . $_POST['description'] . "', "; $query .= "`description`='" . $_POST['description'] . "', ";
} }
if (isset($_POST['words'])) {
$query .= "`words`='" . $_POST['words'] . "', ";
}
if (isset($_POST['nextwordid'])) { if (isset($_POST['nextwordid'])) {
$query .= "`next_word_id`=" . $_POST['nextwordid'] . ", "; $query .= "`next_word_id`=" . $_POST['nextwordid'] . ", ";
} }
@ -174,14 +200,69 @@ function Update_Current_Dictionary() {
} else { } else {
Save_Current_DictionaryAsNew(); Save_Current_DictionaryAsNew();
} }
return false;
}
function Save_New_Word($multiple = false) {
$worddata = json_decode(file_get_contents("php://input"), true);
$dbconnection = new PDO('mysql:host=' . DATABASE_SERVERNAME . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD);
$dbconnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbconnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbconnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$query = "INSERT INTO `words`(`dictionary`, `word_id`, `name`, `pronunciation`, `part_of_speech`, `simple_definition`, `long_definition`) ";
$query .= "VALUES ";
if ($multiple) {
for ($i = 0; $i < count($worddata); $i++) {
if ($i > 0) {
$query .= ", ";
}
$query .= "(" . $_SESSION['dictionary'] . "," . $worddata[$i]['wordId'] . ",'" . $worddata[$i]['name'] . "','" . $worddata[$i]['pronunciation'] . "','" . $worddata[$i]['partOfSpeech'] . "','" . $worddata[$i]['simpleDefinition'] . "','" . $worddata[$i]['longDefinition'] . "')";
}
} else { } else {
echo "not logged in"; $query .= "(" . $_SESSION['dictionary'] . "," . $worddata['wordId'] . ",'" . $worddata['name'] . "','" . $worddata['pronunciation'] . "','" . $worddata['partOfSpeech'] . "','" . $worddata['simpleDefinition'] . "','" . $worddata['longDefinition'] . "')";
}
$query .= ";";
try {
$update = $dbconnection->prepare($query);
$update->execute();
return true;
}
catch (PDOException $ex) {
$errorMessage = $dbconnection->errorInfo();
echo "could not update:\n" . $errorMessage[2] . "\n" . $query;
}
return false;
}
function Update_Word() {
if (isset($_SESSION['dictionary'])) {
$worddata = json_decode(file_get_contents("php://input"));
$query = "UPDATE `words` SET ";
$query .= "`name`='" . $worddata['name'] . "', ";
$query .= "`pronunciation`='" . $worddata['pronunciation'] . "', ";
$query .= "`part_of_speech`='" . $worddata['partOfSpeech'] . "', ";
$query .= "`simple_definition`='" . $worddata['simpleDefinition'] . "', ";
$query .= "`long_definition`='" . $worddata['longDefinition'] . "', ";
$query .= "`last_updated`='" . date("Y-m-d H:i:s") . "'";
$query .= " WHERE `dictionary`=" . $_SESSION['dictionary'] . " AND `word_id`=" . $worddata['wordId'] . ";";
$update = query($query);
if ($update) {
echo "updated successfully";
return true;
} else {
echo "could not update";
}
} }
return false; return false;
} }
function Switch_Current_Dictionary($newdictionaryid, $returndictionary = true) { function Switch_Current_Dictionary($newdictionaryid, $returndictionary = true) {
if ($_SESSION['user'] > 0) {
if (isset($newdictionaryid)) { if (isset($newdictionaryid)) {
if (in_array($newdictionaryid, $_SESSION['dictionaries'])) { if (in_array($newdictionaryid, $_SESSION['dictionaries'])) {
//Clear is_current from all user's dictionaries and then update the one they chose, only if the chosen dictionary is valid. //Clear is_current from all user's dictionaries and then update the one they chose, only if the chosen dictionary is valid.
@ -204,14 +285,10 @@ function Switch_Current_Dictionary($newdictionaryid, $returndictionary = true) {
} else { } else {
echo "no info provided"; echo "no info provided";
} }
} else {
echo "not logged in";
}
return false; return false;
} }
function Delete_Current_Dictionary() { function Delete_Current_Dictionary() {
if ($_SESSION['user'] > 0) {
if (isset($_SESSION['dictionary'])) { if (isset($_SESSION['dictionary'])) {
if (in_array($_SESSION['dictionary'], $_SESSION['dictionaries'])) { if (in_array($_SESSION['dictionary'], $_SESSION['dictionaries'])) {
//Clear is_current from all user's dictionaries and then update the one they chose, only if the chosen dictionary is valid. //Clear is_current from all user's dictionaries and then update the one they chose, only if the chosen dictionary is valid.
@ -229,9 +306,6 @@ function Delete_Current_Dictionary() {
} else { } else {
echo "no current dictionary"; echo "no current dictionary";
} }
} else {
echo "not logged in";
}
return false; return false;
} }
?> ?>