1

I am adding record to database by ajax in CI , so i was trying to return the id of the new record but it's not working , the record has been added but no id is returned .(in ajax code am trying to alert the new record id but it's alerting undefined)

Below is the ajax code:

$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
  success:function(data){

alert(data[0].id);
  $('#register_form')[0].reset();


}  });

This is the controller,

notice that am returning id from create_product method and put it in get_by_id method, and then return result

  if($id=$this->Products_model->create_product($data)){
$result = $this->Products_model->get_product_by_id($id);
 return $result;

       }    

This is my model methods

public function create_product($data){


   $query = $this->db->insert('products',$data);

  if($query){


$id = $this->db->insert_id();

     return $id;

 }else{
    return false;
 } 

    }

 //////////get_by_id_method
    public function get_product_by_id($id){
    $this->db->where($id,'id');
    $query = $this->db->get('products');

    if($query){



        return $query->result();
    }

    }
Pradeep
  • 9,667
  • 13
  • 27
  • 34
Mohamad Alasly
  • 330
  • 3
  • 17

2 Answers2

1

Hope this will help You :

Your ajax should be like this :

$.ajax({
  type:'post',
  url: baseURL + "admin/Products/add_product",
  data:postData,
  success:function(data)
  {
    var response = JSON.parse(data);
    alert(response.id);
    $('#register_form')[0].reset();
  }  
});

Your controller should be like this :

$id = $this->Products_model->create_product($data);
if($id)
{
  $result = $this->Products_model->get_product_by_id($id);
  echo json_encode($result);
  exit;
}

Your model method get_product_by_id should be like this :

public function get_product_by_id($id)
{
  $this->db->where($id,'id');
  $query = $this->db->get('products');
  if($query->num_rows() > 0)
  {
    return $query->row();
  }
}
Pradeep
  • 9,667
  • 13
  • 27
  • 34
  • pls response to this question also : https://stackoverflow.com/questions/51313932/how-can-i-post-data-in-codeigniter-using-ajax – Pradeep Jul 14 '18 at 13:27
0

You may need to echo a JSON with a proper Content-type in your Controller:

$result = [];
$id = $this->Products_model->create_product($data);

if ($id) {
   $result = $this->Products_model->get_product_by_id($id);
}

header("Content-type: application/json");
echo json_encode($result);

So that the response can be an empty object or the query result.