Welcome Guest, Not a member yet? Register   Sign In
Calling method function from Javascript/AJAX
#1

[eluser]Fribos[/eluser]
Hi, i'm codding a CI bassed Chat but i cant update online user's column using AJAX.
User's info comes from CI session class stored on ci_session table on my Database.
Usernames are stored in data_user column as a custom session data. I used serialize PHP method to capture that array and show usernames on a list.

Every 2.5 seconds the code refresh main container loading and reading a html file with chat log (time,username and text)

I want same refresh on online user's column, but now, i must call a method like get_all() and i have no idea how to do it.

fragment from my view
Code:
//Load the file containing the chat log
        function loadLog(){
            var oldscrollHeight = $("#chatbox2").attr("scrollHeight") - 20;
            $.ajax({
                url: "chat/log.html",
                cache: false,
                success: function(html){
                    $("#chatbox2").html(html); //Insert chat log into the #chatbox div
                    var newscrollHeight = $("#chatbox2").attr("scrollHeight") - 20;
                    if(newscrollHeight > oldscrollHeight){
                        $("#chatbox2").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
                    }
                  },
            });
        };

        //Load the users online
        function loadUsr(){
            //document.getElementById('usuarios_chateando')[removed] = '/chatfinal/usuarios_online';
        };

        setInterval (loadLog, 2500);    //Reload file every 2.5 seconds
        setInterval (loadUsr, 2500);    //Reload file every 2.5 seconds

...and this is my Chat_model (i need usuarios_online() to show users online)
Code:
class Chat_model extends Model {
    function Chat_model()
    {
        parent::Model();
    }

    function cant_usuarios_online(){
      $consulta = $this->db->query('SELECT * FROM ci_sessions WHERE user_data<>"" ');
      return $consulta->num_rows();
    }

    function usuarios_online(){

      $consulta = $this->db->query('SELECT * FROM ci_sessions WHERE user_data<>"" ');

        //por cada registro muestro username y guardo la ip
        foreach ($consulta->result_array() as $fila)
          {
          //Le doy formato de array a user_data
          $usr = unserialize($fila['user_data']);
          //guardo la IP del usuario en la variable $ip
          $ip= $fila['session_id'];
          //muestro el username
          echo '<a href="chatfinal/whois/'.$ip.'" target="_blank">'.$usr['username'].'</a><br />';
          }
    }

    function bannear($session_id){
        //capturo datos dela sesion a bannear
        $query = $this->db->query("SELECT ip_address FROM ci_sessions WHERE session_id='".$session_id."'");
        if ($query->num_rows() > 0)
          {
             $row = $query->row();
             $this->db->set('ip', $row->ip_address);
             $this->db->insert('ci_ban');
          }
        }
}

I'll accept any idea, suggestion... everything is welcome
Thank and excuse my horrible english.
#2

[eluser]TaylorOtwell[/eluser]
I think you'll need to make a controller that gives you access to the things you want. Maybe you can make an "API" controller that calls your model for you? Just put the functions that will be called via AJAX in that controller.
#3

[eluser]Fribos[/eluser]
I can make a controller as u said with a function like:
Code:
function get_usrs() {
  $this->chat_model->usuarios_online();
}

But still same problem, i dont know hoy to call it from AJAX
#4

[eluser]nuwanda[/eluser]
Call your controller method from jQuery:

Code:
$.ajax({
    type: "POST",
    url: "/controller/method",
    data: ({parameter_name: parameter_value}),
    dataType: "html",    
    success: function (result) {
      $("#target_element").html(result);
    }
  });

The above code submits parameter_value as parameter_name to controller/method. Upon success, the target_element is filled with the ajax response.

Note the controller and method is relative to your site root.

In your controller, you would have something like:

Code:
function method(parameter_name){

  //do something with parameter_name

  echo result;

}

You need to echo the result, not return it.

Hope that helps.
#5

[eluser]nuwanda[/eluser]
If you don't need to pass parameters in the POST, just leave out the data option in the ajax function.

You may also like to look into using the jQuery load function since you're only returning html from your method.

Code:
$('#result').load('controller/method', function() {

  //#result has already been loaded with the output of method but
  //you can do the rest of your success code here

});

The only issue you may have with load is that when you don't pass params, the function defaults to a GET, which is not allowed by CI (well, sort of). If you do pass params into load, a POST will happen. Perhaps you could just pass in a dummy param to force the POST. Load is certainly a lot simpler to use.

jQuery load function
#6

[eluser]Fribos[/eluser]
Thank you Lab Assistant !!!!!!!!!!
It worked perfect. I just deleted data parameters as u said and problem solved
Thanks again
#7

[eluser]Fribos[/eluser]
Hi, me again.
What about if i need to execute a function for session destroy when the user leaves?
I'm codding something like this:

On my controller
Code:
function destruir_sesion(){
        //destruyo sesion
        $this->session->sess_destroy();
    }

On my &lt;head&gt; view
Code:
function destruir_sesion(){
       if (document.location.href=='xxxxxxxxxxxx/chatfinal') {
            $.ajax({
              type: "POST",
              url: "xxxxxxxxxxxx/chatfinal/destruir_sesion",
              success: function (result) {
              }
            });
       }
    }

On my view body div
Code:
onunload="destruir_sesion()"

I cant understand AJAX sintax, so if u can help me again i'll thank you again.
Where can i find a good ajax tutorial for begginers ?
Thanks
#8

[eluser]nuwanda[/eluser]
The jQuery website has excellent tutorials.
#9

[eluser]vitoco[/eluser]
[quote author="nuwanda" date="1290828932"]The jQuery website has excellent tutorials.[/quote] .... e.g. RTM !!!




Theme © iAndrew 2016 - Forum software by © MyBB