1

My server code is returning json data, which have select mysql query. Now I have to parse this information and I need to fill there json information into table, How I will do that?

My server code

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","2323");
mysql_select_db("service");

if(isset($_POST['type']))
{
    if($_POST['type']=="carpenter"){
        $startDate=$_POST['startDate'];
        $endDate=$_POST['endDate'];
        $query="select * from booking where scheduledDate between $startDate AND $endDate"; 
        $result=mysqi_query($query);
        $count=mysql_num_rows($result);         
        $retVal=array();

        while($row=mysqli_fetch_assoc($result)){
            $$retVal[]=$row;
        }
        echo json_encode($retVal);
    }
} else{
    echo "Invalid Format";
}

My script

<script>
    function fetchData2(){
      $(".data-contacts2-js tbody").empty();
      var startDate=$('#datepicker1').val();
      var endDate=$('#datepicker2').val();
      $.ajax({
              url: "http://localhost/service/cleaning.php",
              type:"POST",
              dataType:"json",
              data:{type:"carpenter", startDate:startDate, endDate:endDate},
              ContentType:"application/json",
              success: function(response){                           
                 alert(obj);
             },
             error: function(err){
                alert("fail");
            }       
        });             
     }  

     $(document).ready(function(){
         $(".data-contacts2-js tbody").empty();               
         $('#fetchContacts2').click(function() {
                 fetchData2();
         });
      });

 </script>

My html code

<div class="block-content collapse in">
      <div class="span12">
        <table class="data-contacts2-js table table-striped" >
             <thead>
                    <tr>
                          <th>ID</th>
                          <th>Customer Name</th>
                          <th>Customer Mobile</th>
                          <th>Customer Email</th>
                          <th>Address</th>
                          <th>Date</th>
                          <th>Time</th>
                          <th>Status</th>
                    </tr>
          </thead>
             <tbody>

             </tbody>
      </table>                                  
  </div>
 <button id="fetchContacts2" class="btn btn-default" type="submit">Refresh</button>                         
          </div>

My Json format is

[
    {
        "b_id": "101",
        "cust_name": "qwq",
        "cust_mobile": "323232323",
        "cust_email": "u@gmail.com",
        "cust_address": "kslaksl",
        "scheduledDate": "2015-02-26",
        "scheduledTime": "14:30:00",
        "sc_id": "3",
        "sps_id": "1"
    }
]

My dataBase table: enter image description here

Neelabh Singh
  • 2,600
  • 12
  • 51
  • 88
  • you could build your markup table rows from the response using `$.each` then just `.html(markup)` on the `tbody`. is this a typo? `$result=mysqi_query($query);` – Kevin Feb 19 '15 at 06:37
  • @Ghost, thanks for reply, could you explain much more.. – Neelabh Singh Feb 19 '15 at 06:44
  • could u show ur json response – Nibin Feb 19 '15 at 06:47
  • @Outlooker, thanks for reply, I add my database snapshot, please see it, I am new in JSon, I dn't know How would be response.. – Neelabh Singh Feb 19 '15 at 06:51
  • @neelabhsingh just use that function inside the success block, `$.each(response, function(index, element){ // build html here });` and remove that `ContentType:"application/json",` you don't need that – Kevin Feb 19 '15 at 06:54
  • @Ghost, Why we don't need contentType.. – Neelabh Singh Feb 19 '15 at 06:55
  • @neelabhsingh you don't need your content type to be json, just leave it so it defaults to form-urlencoded – Kevin Feb 19 '15 at 06:59

2 Answers2

1

The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. Inside the ajax success try the each function and loop through the response data that has been received from the php file.Hope that gives you an idea mate.. :)

        success: function(response){                           
             $.each(response, function(idx, obj) {
                $('table tbody').append(
                $('<tr>')
                    .append($('<td>').append(obj.id))
                    .append($('<td>').append(obj.cust_email))
                    .append($('<td>').append(obj.cust_mobile))
                );
             });
         },

FYI

$.each

Nibin
  • 3,922
  • 2
  • 20
  • 38
1

One way is to use $.each and start building your markup table rows, then putting it inside the tbody tag.

You could just build them inside the success block. Here's the basic idea.

$.ajax({
    url: "http://localhost/service/cleaning.php",
    type: "POST",
    dataType: "json",
    data: {type:"carpenter", startDate:startDate, endDate:endDate},
    success: function(response){                
        var rows = '';           
        $.each(response, function(index, element){
            rows += '<tr>'; // build the row
                $.each(element, function(key, val){
                    rows += '<td>' + val + '</td>'; // build the value
                });
            rows += '</tr>';
        });
        $('table tbody').html(rows);
    }   
});

Sidenote: Based on your code, your mixing MySQLi and MySQL functions.

Obligatory Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

I suggest use PDO with prepared statements:

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
$db = new PDO('mysql:host=localhost;dbname=service', 'root', '2323');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if(isset($_POST['type'])) {
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];
    $query = 'SELECT * FROM booking WHERE scheduledDate BETWEEN :startDate AND :endDate'; 
    $select = $db->prepare($query);
    $select->bindParam(':startDate', $startDate);
    $select->bindParam(':endDate', $endDate);
    $select->execute();

    $data = $select->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data);
    exit;
}
Community
  • 1
  • 1
Kevin
  • 41,694
  • 12
  • 53
  • 70