سؤال

I'm playing with jQuery's $.ajax and I'm not sure how I should be doing the following:

Here's my javascript (right now its just embedded in the html page)

$.ajax({
    type: 'GET',
    url: 'DBConnect.php',
    data: '',
    dataType: 'json', 
    success: function(data) {

        console.dir(data);
    },
    error:function (xhr, ajaxOptions, thrownError) {
        dir(thrownError);
        dir(xhr);
        dir(ajaxOptions);
    }
});

Here is what DBConnect.php looks like:

$username = "root";
$pass = "pass";
$host = "127.0.0.1";
$dbname = "test";

//queries
$table = "events";
$fetchAll = "SELECT * FROM $table";

try {
    $DB = new PDO("mysql:host=$host;dbname=$dbname", $username, $pass);
    //_WARNING uncommented when debugging
    $DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    //$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $query = $DB->query($fetchAll);
    $query->setFetchMode(PDO::FETCH_OBJ);

    while($row = $query->fetch()) {
        echo json_encode($row);
    }

} catch(PDOException $e) {
    echo $e->getMessage();
}

$DB = null;

Doing this I get a syntax error. I thought I could get away with returning every row as a json object, but clearly that doesn't work. I could just add all the row objects to one array and convert that to json, but I wanted to know if there was a better\more efficient way to do this.

هل كانت مفيدة؟

المحلول

Change the while loop:

$temp = array();
while($row = $query->fetch()) {
    $temp[] = $row;
}
echo json_encode($temp);

Try this, and let me know if that helps!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top