Jed Jamir
Jed Jamir

Reputation: 77

data output from database through ajax jquery

how can i get the data from my database when i click each of my button's id my controller function

public function ajax (){
   $resultdata = $this->Booking_model->roominfo();
   echo json_encode($resultdata);
}

here's my button with its data-room-id and class

<button class="bkng bkn-room trans_200" data-room-id ="1">BOOK NOW</button>

here's my model

public function roominfo() {
  //if(isset($_POST["id"]))
  //{
        $sql = "Select name, price from rooms WHERE room_id = 'id'";
        $result =  $this->db->query($sql);
        return $result->result_array();
  //}

my ajax jquery with its button class and data-room-id

$(document).ready(function() {
        $(".bkng").on("click", function(event) {
              event.preventDefault(); 
            var id = $(this).data('room-id');
                console.log(id); 
                if(id != '') 
                {
                    $.ajax( {
                    type:"get",
                    url : "Pages/ajax",
                    data:{id:id}, 
                    success:function(data)
                    {
                        alert(data);
                        result = JSON.parse(data); 
                        $('#test1').append(result[0]['name']);
                        $("#test2").append(result[0]['price']);
                        $("#test3").append(result[0]['price']);
                        console.log(data); 
                    }
                });
            } 
            });
        }); 

it always says in the console error that Uncaught TypeError: Cannot read property 'name' of undefined

Upvotes: 2

Views: 114

Answers (1)

Vickel
Vickel

Reputation: 7997

you get this error, because your query is not returning anything, as you might not have a room with the id = 'id'. Therefore JSON.parse returns this error.

so first you need to fix your model building a valid query, like:

function roominfo() {
    $id=$_POST["id"];
    $query=$this->db->select('name, price')
                    ->where('room_id', $id)
                    ->get('rooms');
    return ($query->num_rows())? $query->result_array():false;  
}   

then in your ajax success, you can check for the data returned with: console.dir(data) and not with alert or console.log as they will not show you the array structure

you also should check the eventuality of no data (false) was returned:

  type: 'POST',
  success:function(data)
    {
        console.dir(data);
        if (data){
            result = JSON.parse(data); 
            $('#test1').append(result[0]['name']);
            $("#test2").append(result[0]['price']);
        }
        else
        {
            $('#test1').append('no records found']);
        } 
    }

Upvotes: 1

Related Questions