Reputation: 12718
I'm trying to get two distinct results from AJAX calls. I pass in _functionToRun
to the PHP file, which uses a switch statement to determine which function to run.
In the PHP file, I echo out two different arrays of words... newQuestWords()
should only return some of the words. parseHoveredText()
should return all vocab in the database.
Yet it seems when I echo out both, just all of the vocab is returned...
For example, in the JavaScript, log(hoveredWords[i]);
should show all of the vocab available in the database, as returned from `parseHoveredText()
function, but it doesn't show anything.
Why is that?
JavaScript:
$(document).ready(function() {
//initially append words to word bank
$.getJSON("php/Quests.php", { "_questNum" : questNum, "_functionToRun" : 1},
function(returned_data) {
wordsArray = returned_data;
$.each(wordsArray, function(key, value) {
$(".wordBank_Words").append("<span class='bankword' data-display-word='" + key + "' ><b>" + key + "</b>: " + value + "</span><br/>");
}
);
});
//get all chinese/english words for hover over translation
$.getJSON("php/Quests.php", {"_functionToRun" : 2},
function(returned_data) {
hoveredWords = returned_data;
for (var i = 0; i < hoveredWords.length; i++) {
log(hoveredWords[i]);
}
});
PHP:
<?php
//if user's input is correct, increment task number, get next vocabulary
$functionToRun = (isset($_GET['_functionToRun'])) ? $_GET['_functionToRun'] : 1;
parseHoveredText();
switch ($functionToRun)
{
case 1:
newQuestWords();
break;
case 2:
parseHoveredText();
break;
default:
echo "defaulted...";
}
function newQuestWords () {
include 'DbConnect.php';
$questNumber = (isset($_GET['_questNum'])) ? $_GET['_questNum'] : 1;
$qry =
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = " . $questNumber;
$sql = $mysqli->query($qry);
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
echo json_encode($wordsArray);
}
function parseHoveredText () {
include 'DbConnect.php';
$qry =
"SELECT v.*
FROM vocab v";
$sql = $mysqli->query($qry);
$hoveredWords = array();
while ($row = $sql->fetch_assoc()) {
$hoveredWords[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
//return Chinese and English Words
echo json_encode($hoveredWords);
}
?>
Upvotes: 0
Views: 213
Reputation: 2323
Dump return_data, it is json object not an array you can iterate. You can iterate through it this way
...
function(returned_data) {
for (word in returned_data) {
console.log(word);
}
}
...
Or with $.each
...
$.each(returned_data, function(key, value) {
console.log(value);
}
...
Upvotes: 1