简体   繁体   中英

show JSON data(from php file) in table using ajax

I hava a php code as shown below serverdata.php

<?php

require_once('database.php');
header("Content-type: application/json");  

$sql = "SELECT * FROM user";
$result = mysql_query($sql);
$uid = array();
$uname = array();


while($row = mysql_fetch_assoc($result)) 
   {
     $dataarray[] = $row;
   }

  echo json_encode($dataarray); 
?>

which produce the following output in JSON format:

[{"id":"1","username":"Sagun","password":"61b51ae250c7e7505191e4d5e6240c04"},{"id":"2","username":"roshan","password":"d6dfb33a2052663df81c35e5496b3b1b"},{"id":"17","username":"rajiv","password":"9a9af43c15771eaf3b2db8bb28a2829d"}]

All i want is to get the data from above php file that is in json format and display it in table in another page using AJAX. Please guide me through it.

 ID USERNAME PASSOWRD 
  1   sagun   61b51...    
  2   roshan  d6dfb.. 
 17   rajiv   9a9af..

This is the ajax function to get your json data from php output, try to modify as you need.

<script type="text/javascript">
$(function() {
    $.ajax({
        type      : 'POST',
        url       : 'YOUR_PHP_URL',
        data      : {},
        dataType  : 'json',
        error     : function (a, b, c) 
        {

        },
        success   : function(data) 
        {
            console.log( data );
        }
    });
});
</script>

Don't forget to include the jQuery library. https://developers.google.com/speed/libraries/#jquery

This code for build table in jquery

<script type="text/javascript">
function jsonData()
{

    $.ajax({
        type:'post',
        url:"serverdata.php",
        datatype:'json',
        success:function(data)
        {
            var jdata=$.parseJSON(data);
            ///console.log(jdata);
            $(function(){
                $.each(jdata,function(i,item){
                    var tr = $('<tr>').append(
                    $('<td>').text(item.id),
                    $('<td>').text(item.name),
                    $('<td>').text(item.email),
                    //$('<td>').text(item.password),
                    $('<td>').text(item.mob_num),

                );
                $("#tableId tbody").append(tr); 
                //console.log(tr.wrap('<p>').html());
                })
            })

        }
    })
}

database.php

    <?php
try{
    $db = new PDO('mysql:host=localhost;dbname=testing', "root" , "");


}catch(PDOException $e){
    print "error in connection" . $e->getMessage();
}

home.html

    <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JSON data</title>
</head>
<body>

  <table id="demoTable">
    <thead>
      <tr>
        <td ><label>Id</label></td>
        <td ><label>Username</label></td>
        <td ><label>Password</label></td>
      </tr>
    </thead> 
    <tbody>  
    </tbody>  
  </table>
  <script src="jquery.min.js" type="text/javascript"></script>
  <script src="detail.js" type="text/javascript"></script>
</body>
</html>

details.js

$(document).ready(function() {

    $.ajax({
        url:'serverdata.php',
        type:'POST',
        success:function(data){

            var result = $.parseJSON(data);
            $.each(result, function(key, value){
                $.each(value, function(k, v){
                    if(k === "id"){
                        $("#demoTable >tbody:last").append(
                            $('<tr>').append(
                                $('<td>').append(v)
                                .append(
                                    $('</td>').append(
                                        $('</tr>')
                                        )
                                    )
                                )
                            );
                    }
                    if(k === "username"){
                        $("#demoTable >tbody >tr:last").append(

                            $('<td>').append(v)
                            .append(
                                $('</td>')

                                )

                            );
                    }
                    if(k === "password"){
                        $("#demoTable >tbody >tr:last").append(

                            $('<td>').append(v)
                            .append(
                                $('</td>')

                                )

                            );
                    }
                });
            });
        }
    })      
});

serverdata.php

<?php
require_once 'database.php';
$data = array();
$stmt = $db->query('SELECT * FROM user');
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($row as $key => $value) {
    $data[$key] = $value;
    $result = json_encode($data);
}
echo $result; 

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