0

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!

  • Does this answer your question? [how to alert javascript object](https://stackoverflow.com/questions/3580754/how-to-alert-javascript-object) – steven7mwesigwa Jun 24 '22 at 19:08
  • I tried this and it shows that the result/object is actually "null". Any reason why the result would be null? I've double checked the database fields etc and everything is as it should be, so not sure why it's not retrieving the data from the database :( – programmingnewb Jun 25 '22 at 08:23
  • Did you cross-check to confirm if the `$productid` is reaching the controller? – steven7mwesigwa Jun 25 '22 at 08:56
  • Yup, 100% is reaching as I've tried passing $productid back to the ajax (instead of $partno from the database) and it shows up fine – programmingnewb Jun 25 '22 at 17:42

1 Answers1

0

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.

Antony
  • 3,875
  • 30
  • 32