Kuszluk Kuszluk - 3 months ago 8
PHP Question

Getting array of objects from database using ajax

I want to download comments from database and display them on my page. Current code returns syntax error as php file does not return proper json file.

My php code (no connection problems so only fetching part).

if ($result->num_rows > 0){

while($row = $result->fetch_assoc()) {

echo json_encode(array(
"id" => $row["id_com"],
"nick" => $row["com_nick"],
"email" => $row["com_email"],
"text" => $row["com_text"],
"data" => $row["com_data"],
"ocena" => $row["ocena"]
));
}


Returned value.

{"id":"1","nick":"my_nick","email":"g@go.pl","text":"content!","data":"2016-08-03","rate":"5"}{"id":"4","nick":"ra","email":"hat@gon.ha","text":"Hat","data":"2016-08-03","ocena":"1"} ect...


Ajax request (I think problem lies here)

$.ajax
({
url: "/commdown.php",
dataType: 'json',
success: function(data)
{
alert(

"id: " + data.id +
"\nnick: " + data.nick +
"\nemail: " + data.email +
"\ntext: " + data.text +
"\ndata: " + data.data +
"\nocena: " + data.ocena

);
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});


I think the problem is that I'm downloading multiple objects with single ajax request instead of calling a request for every comment separately.

Answer

Use a array to append all the data to it then echo that encoded data, use a loop in the ajax to display it on the page/alert box

if ($result->num_rows > 0){
    $data = [];
    while($row = $result->fetch_assoc()) {

        $data[] = array(
            "id" => $row["id_com"],
            "nick" => $row["com_nick"],
            "email" => $row["com_email"],
            "text" => $row["com_text"],
            "data" => $row["com_data"],
            "ocena" => $row["ocena"]
        );
    }
header('Content-Type: application/json');
echo json_encode(data);

js:

$.ajax
    ({
        url: "/commdown.php",
        dataType: 'json',
        success: function(retdata)
        {
          $.each(retdata,function(i,data){
              alert(  

                      "id: " + data.id +
                      "\nnick: " + data.nick +
                      "\nemail: " + data.email +
                      "\ntext: " + data.text +
                      "\ndata: " + data.data +
                      "\nocena: " + data.ocena

              );
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) 
        { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); 
        }  
    });
Comments