Welcome Guest, Not a member yet? Register   Sign In
simple ajax count(*) example?
#1

[eluser]new_igniter[/eluser]
Does anyone have a quick ajax script that could call a model, count a table, and return a value?
#2

[eluser]sandwormusmc[/eluser]
Sure.

1. Create a function in your main controller called setAction (for below).
2. Point your AJAX to your main controller.
3. Create the model function to do the count of the table.

HTML:
Code:
&lt;a href="#" onClick='doAjax(countMyTable);'&gt;Click me for AJAX goodness</a>
<div id='countMyTable'>&nbsp;</div>

JavaScript to include in your HTML:
Code:
var baseURL='&lt;?=base_url()?&gt;index.php/<REPLACE WITH MainControllerName>';
function doAjax(target) {
    var url  = baseURL+'/setAction/'+target;
    var ajax = new Ajax(url, {
        method: 'get',
        update: $(target)
    }).request();
}

PHP in your main controller:
Code:
public function setAction(){
  $tableName=$this->CI->uri->segment(3);
  $this->CI->load->model('count_model','',TRUE);
  $result=$this->CI->count_model->countMeh($tableName);
  print_r($result);
}

PHP in count_model:
Code:
&lt;?
class count_model extends Model {

    public function __construct(){
        parent::Model();
    }

    public function countMeh($tableName){
        $sql="SELECT COUNT(*) FROM `$tableName`;";
        $result=$this->db->query($sql);
        $count=$result->row();
        return $count;
    }
}

That should do it ... change the print_r in the main controller to make the output more readable.

Does that work? Tongue
#3

[eluser]new_igniter[/eluser]
that's awesome! thanks.
#4

[eluser]sandwormusmc[/eluser]
It'll get a lot more complex once you start having multiple actions you want to handle from your AJAX calls. This is why it's a good idea to have a setAction function that parses the URL variables and decides what to do from there. It all seems a little hackish to me, but the way I've been doing action handling is by including a '_' between the type of data I'm working on and the action to perform on it (i.e. edit_server or delete_person).

If anyone knows of a more elegant approach to action handling through AJAX I'd love to hear it ... Smile




Theme © iAndrew 2016 - Forum software by © MyBB