Apply for Zend Framework Certification Training

Jquery





<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-size:16px"><strong>How to Display data from database in JSON format using Ajax and PHP</strong></span><br />
<br />
A very common use of JSON is to read data from a web server and then display these data into a web page.</p>

<p>JSON is text, so when we want to exchange text as data between a browser and web server we can use JSON. In this tutorial, I will teach you how to get data from database in JSON format using Ajax and PHP. PHP has some default functions which can easily handle any JSON string. json_encode() function converts any PHP objects into JSON. Similarly, json_decode() function converts any JSON into PHP array object.</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong> So, for better understand, follow the following example, it will help you to know how to get data from</strong></p>

<p>database in JSON format using Ajax and PHP. In this example, we will insert a roll number in the input box, it returns corresponding student details from the MySQL database in JSON format and displays in the web page.</p>
                                    

               Let See code

    define('HOST','localhost');
    define('USER','root');
    define('PASSWORD','');
    define('DATABASE','jquery');
    
    $conn = mysqli_connect(HOST,USER,PASSWORD,DATABASE);

    include 'db.php';
    $select = "select * from company";
    $select_mq = mysqli_query($conn,$select);
    while($mfa_data = mysqli_fetch_assoc($select_mq)){
        $data['company_list'][] = $mfa_data;
    }
    
    echo json_encode($data);
    exit();
 

Index.php

<body onload="getcompanylist();">
<table border="1" id="company_data">
</table>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
    function getcompanylist(){
        var roll = 1;
        $.ajax({
           url:'getcompanylist.php',
           type:'post',
           dataType:'json',
           data:{roll:roll},
           success:function(data){
               $.each(data.company_list ,function(i,post){
                       var newrow = "<tr><td>"+post.company_name+"</td><td>"+post.company_address+

                                          "</td><td>"+post.company_type+"</td></tr>";
                      $(newrow).appendTo("#company_data");
               })
           }
        });
    }
</script>

 

 


    

 

 

 




 

< Ajax pagination with search filter php Last >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top