Frage

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);
War es hilfreich?

Lösung

Don't do this. You'd be better off building a PHP array, then sending it to the client via JSON, e.g.

$data = array();

SELECT word, translation, example_sentence_1 FROM ...

while ($row = $stmt->fetch()) {
   $data['rawvobab'][] = $row;
}

SELECT ...

while (...) {
    $data['optionVocab'][] = $row;
}

echo json_encode($data);

Using json_encode ENSURES that the "code" you're sending to the client is syntactically valid Javascript. Right now your code is vulnerable to injection attacks. E.g. consider what happens if your example sentence contains even a single ' - you'll be producing a javascript syntax error and killing the rest of that code block.

Andere Tipps

The json_encode method is fine, but watch for bugs in some versions of PHP where json_encode(array(1.2)) could return '[1,2]' instead of the correct '[1.2]' depending on locale settings. If you never call setlocale() in your code or any of the libraries, you’re probably safe, though.

I wrote a “minijson” (now full-featured though) – https://fusionforge.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=fusionforge/fusionforge.git;a=blob;f=src/common/include/minijson.php;h=c9020f4e7b826a88851b1149ddeb10a682f777c9;hb=HEAD – which fixes these problems and works with PHP versions old enough to not have json_encode (whose licence is also problematic, which is why it’s removed from distros now).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top