Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Codeigniter autocomplete with ajax

I’m adding private messaging to my site. In the Recipient text field in my form, I want to suggest valid usernames when someone starts typing. After reading tutorials and studying some scripts I made the following code for suggesting usernames from my database table named users. It works but I’m not certain how correct and secure it is.

Jquery (using the Jquery UI autocomplete plugin):

$(function() {                     
    $( "#username" ).autocomplete({ //the recipient text field with id #username
        source: function( request, response ) {
            $.ajax({
                url: "http://localhost/mysite/index.php/my_controller/search_username",
                dataType: "json",
                data: request,
                success: function(data){
                    if(data.response == 'true') {
                       response(data.message);
                    }
                }
            });
        },
        minLength: 1,
        select: function( event, ui ) {
            //Do something extra on select... Perhaps add user id to hidden input    
        },

    });
}); 

Controller (for simplicity I did not use a model although I plan to)

function search_username()
{
        $username = trim($this->input->get('term')); //get term parameter sent via text field. Not sure how secure get() is

        $this->db->select('id, username'); 
        $this->db->from('users');
        $this->db->like('username', $username);
        $this->db->limit('5');
        $query = $this->db->get();

        if ($query->num_rows() > 0) 
        {
            $data['response'] = 'true'; //If username exists set true
            $data['message'] = array(); 

            foreach ($query->result() as $row)
            {
                $data['message'][] = array(  
                    'label' => $row->username,
                    'value' => $row->username,
                    'user_id'  => $row->id
                );
            }    
        } 
        else
        {
            $data['response'] = 'false'; //Set false if user not valid
        }

        echo json_encode($data);
} 
like image 334
CyberJunkie Avatar asked Jul 30 '26 05:07

CyberJunkie


1 Answers

There is one edit that I would recommend making...

I would enable XSS protection by passing a second argument TRUE to get()

    $username = trim($this->input->get('term', TRUE));
like image 99
jondavidjohn Avatar answered Aug 01 '26 20:08

jondavidjohn