skip to Main Content

I am working with ajax and Codeigniter, I send a request by ajax to the controller and get a response like the below code:-

Controller Response:-

array(1) {
  [0]=>
  object(stdClass)#29 (1) {
    ["absent"]=>
    string(1) "4"
  }
}

the question is here that how can I get 4 from the response?

ajax call:-

 $('#staff').change(function(){
    let staff_id  = $(this).val();
    let month = $('#month').val();

    $.ajax({
        url:base_url+'hr/home/getStaffAbsentDay',
        type:'POST',
        data:{
            'staff_id':staff_id,
            'month':month
        },
        success:function(response){
            console.log(response);
            
        }
    })
});

Controller:-

public function getStaffAbsentDay(){
    $id =$this->input->post('staff_id');
    $month=$this->input->post('month');
    $this->stuff_model->get_staff_absent_days($id,$month);
}

Model:-

public function get_staff_absent_days($id,$month){
  $year =jDateTime::date('Y',false,false,true,'Asia/Kabul');
  $this->db->select('absent'); 
  $this->db->from('staff_attendance');   
  $this->db->where('staf_id', $id);
  $this->db->where('year', $year);
  $this->db->where('month', $month);
  $d=$this->db->get()->result();
  return json_encode($d);
}

2

Answers


  1. It looks like your PHP is using var_dump to output its data. This is a debugging tool for PHP. Don’t use it to write APIs!

    Output the data using a standard format instead:

    header("Content-Type: application/json");
    echo json_encode($your_data);
    

    Then response will be a JS array instead of a string.

    Login or Signup to reply.
  2. Model:-

    public function get_staff_absent_days($id,$month){
      $year =jDateTime::date('Y',false,false,true,'Asia/Kabul');
      $this->db->select('absent'); 
      $this->db->from('staff_attendance');   
      $this->db->where('staf_id', $id);
      $this->db->where('year', $year);
      $this->db->where('month', $month);
      $d=$this->db->get()->result();
      return $d;
    }
    

    Controller function:-

       public function getStaffAbsentDay(){
            
            $id =$this->input->post('staff_id');
            $month=$this->input->post('month');
       
       $your_array__data = $this->stuff_model->get_staff_absent_days($id,$month);
          echo json_encode($your_array__data);
       
    }
    

    jQuery / Ajax Call :-

    and Now Your response will be a JS array instead of a string Format.

      success:function(response){
         var data = JSON.parse(response);
          console.log(data[0].absent)
          // $('#staffAbsentDays').html('success')
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search