I'm trying to use Ajax to pull info from a Database for an HTML 5 game. As you can see from the code below, I want to echo JavaScript in the PHP so that it pushes variables stored in the database into the arrays 'rawVocab' and 'optionVocab'. But when I check the length of these arrays, I find they're empty.
Additionally, this line console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
does not appear to be called. There may be something wrong with my implementation of eval()... not sure.
By the way, my code uses the Google Closure library.
var rawVocab = new Array();
var optionVocab = new Array();
var request = new goog.net.XhrIo();
goog.events.listen(request, "complete", function(){
if (request.isSuccess()) {
response = request.getResponseText();
eval(response);
// print confirm to the console
console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
} else {
// print error info to the console
console.log(
"Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(),
" - message: ", request.getLastError()
);
}
});
request.send("load_vocab.php");
Here's load_vocab.php...
$data = array();
try {
$conn = new PDO('mysql:host=localhost;dbname=tygrif_school', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT word, translation, example_sentence_1 FROM vocabulary_game WHERE game_type = :game_type');
$stmt->execute(array('game_type' => 'target'));
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$data['rawVocab'][] = $row;
}
$stmt = $conn->prepare('SELECT word, translation, example_sentence_1 FROM vocabulary_game');
$stmt->execute(array());
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$data['optionVocab'][] = $row;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($data);