I'm new to codeigniter 4 and having some issues retrieving data from my database.
In my controller, I have:
$partno = model(Ecart_model::class)->getPartno($productid);
echo json_encode($partno);
In my model, I have:
public function getPartno($productid){
$db = db_connect();
$partno = $db->table('products')->select('partno')->where('id', $productid)->get();
return $partno;
}
In my Ajax function, I have:
function addtoecart(ip,productid){
var postData = {ip: ip, productid: productid};
$.ajax(
{
url : 'https://www.myurl.com/ecart/add',
type: 'POST',
data : postData,
dataType: "json",
success: function(result) {
alert(result);
},
});
}
Everything in terms of functionality works (which isn't the issue). The issue I am having is the value/data that is retrieved from the database and is passed back to the Ajax function, on success, the alert shows: [object Object] instead of the actual value retrieved from the database
I hope that makes sense? Do you know what is wrong with the code?
Thanks!
Is this not the answer?
public function getPartno($productid){
$db = db_connect();
$row = $db->table('products')->select('partno')->where('id', $productid)->get()->getRowArray();
return $row['partno'];
}
I'm also not sure that Jquery decodes json data on an ajax result so I would also try JSON.parse(result)
as well. Although as you're returning an int
you probably don't need the JSON at all and could simply output it.