0

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.

2
  • This will just return the first row of your result... Commented May 14, 2014 at 20:13
  • Concat the rows first, then json_encode(). Commented May 14, 2014 at 20:13

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

I figured I would have to do that. But is this an appropriate way to pass json data back to the browser? I guess I'm really asking if my general approach is flawed -should have made that clearer in my question.
Your original approach is indeed flawed. You cannot continue to echo results in a while loop. The output would not be a valid json object (it would be a string of concatenated json objects).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.