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!

4
  • Does this answer your question? how to alert javascript object Commented Jun 24, 2022 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 :( Commented Jun 25, 2022 at 8:23
  • Did you cross-check to confirm if the $productid is reaching the controller? Commented Jun 25, 2022 at 8: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 Commented Jun 25, 2022 at 17:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.