remyremy
remyremy

Reputation: 3758

call CodeIgniter Model with ajax

I'm trying to call a function in one of my model but I would like to do so without going through a controller, is that possible? The code provided below doesn't work, I get 404 Not Found

Javascript:

$.ajax({
    type: "POST",
    url: "/myApplication/usersModel/get_cash_player",
    success: function(result){
       alert("ok");
    }
});

My model (located in usersModel.php) :

public function get_cash_player(){                
   $currentUserID = $this->usersModel->get_user_id();
   $query = $this->db
       ->select('cash')
       ->from('users')
       ->where('id_player', $currentUserID)
       ->get();
   return $query->row('cash');      
}

Alternatively I could create a controller calling the method in the model but I would like to know if this shortcut is possible.

Update 1: Okay, now comes the next question. For some of my controller I'm using a custom Helper because I want them available in several controllers. That works fine when calling them via PHP but can I create one for the get_cash_player controller mentioned above (and in the comments) and call it through Ajax?

I tried this but it is still not found:

if(!function_exists('get_cash_player')){
    function get_cash_player(){  
        $ci=& get_instance();
        $cash = $ci->usersModel->get_cash_player();
        return $cash;
    }
}

Upvotes: 2

Views: 2229

Answers (2)

Prakash
Prakash

Reputation: 335

Directly calling the Model isnt possible, the Controller is the one always handling the process to and from View and the Model. This is the proper Codeiginter MVC approach,

workflow source: https://www.codeigniter.com/user_guide/overview/appflow.html

this link also may help you https://www.codeigniter.com/user_guide/overview/mvc.html

But, you can do like this: use your ajax function to call a controller function to pass data through. The controller will handle the process with the model, and return data back to the ajax function.

Upvotes: 2

DFriend
DFriend

Reputation: 8964

No. It is not possible. All incoming server requests are routed to controllers.

Upvotes: 0

Related Questions