简体   繁体   中英

Display data from php script in a table using ajax

I am looking to display data by running some query via php script and then using ajax to show it on an html page.

I have a php script that echos the data from a sql query in json format. The output looks like this:

{"Username":"Server","RICS":12739,"Exclusive_RICS":0}{"Username":"eikon1","RICS":4,"Exclusive_RICS":0}{"Username":"balbla","RICS":552,"Exclusive_RICS":0}{"Username":"somename","RICS":221,"Exclusive_RICS":201}

I would like to display this data using an $.ajax call.

I did some research and came up with this:

$(document).ready(function(){

$.ajax({

    url : 'query.php',
    type : 'POST',
    data : {
        //'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        window.alert(data.Username)
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

});

However, it's not working properly. I just get this alert:

在此处输入图片说明

I am new to js/ajax/php so excuse me if I missed something simple.

Any help is appreciated. Thanks!

EDIT:

php code:

    $sql = 'select * from table';

$retval = sqlsrv_query($conn,$sql);
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}


while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
    echo json_encode($row);
}

sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);

EDIT 2: Managed to get the output of php in correct JSON format through this. Now just need to display this using ajax.

while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
    $rows[] = $row;
}
echo json_encode($rows);

Looping through your SQL result set and echoing each row separately produces an invalid JSON format. Instead you should json_decode the entire SQL result set.

Here's how you can update your PHP code so that it outputs the correct format:

php code:

$sql = 'select * from table';

$retval = sqlsrv_query($conn,$sql);
if(! $retval ) {
  die('Could not get data: ' . mysql_error());
}

echo json_encode( sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) );

sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);

There may be one more step necessary in your AJAX success callback. You'll have to JSON.stringify the result because PHP will send it back as plain text:

success : function(data) {              
    var result = JSON.stringify( data );
    window.alert(result.Username)
}, 

Thanks for the help everyone. I was eventually able to figure out the issue.

  • First of all, as pointed by users, my json format was not right. I fixed that with the solution in my edit.
  • Secondly, I had to reference my php directly with the exact address. I think it has to do with running queries from same server. Not sure perfectly.
  • Thirdly, i tried a plain ajax call and even that was failing. It turns out my browser (chrome) needed a clean up. I cleared my cookies and it started to work fine. Why it was acting weird? I have no idea!
  • Finally, now I needed to display the data in a table format and update the table frequently. I am still working with that but this is what I got going for me right now:

     $(document).ready(function() { (function poll() { $.ajax({ url : 'http://localhost/scripts/query.php', type : 'POST', data : {}, dataType:'json', success : function(response) { var json_obj = $.parseJSON(JSON.stringify(response)); var output=""; for (var i in json_obj) { output+="<tr>"; output+="<td>" + json_obj[i].time.date + "</td>" + "<td>" + json_obj[i].username + "</td>" + "<td>" + json_obj[i].rics + "</td>" + "<td>" + json_obj[i].exclusive_rics +"</td>"; output+="</tr>"; } $('#table_content').html(output); }, error : function(request,error) { alert("Request: "+JSON.stringify(request)); } , dataType: "json", complete: setTimeout(function() {poll()}, 5000), timeout: 2000 }) })(); 

    });

I really don't understand why this was so hard to do. I am sure this is a common scenario and I really wish there was a more straightforward way of doing this. Hopefully, my final code will avoid others from wasting so much of their time. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM