0

Tankauth already has inbuilt function to check if a username is available or not. the function is located in library and model .

library function

function is_username_available($username)
{
    return ((strlen($username) > 0) AND $this->ci->users->is_username_available($username));
}

function in model

function is_username_available($username)
{
    $this->db->select('1', FALSE);
    $this->db->where('LOWER(username)=', strtolower($username));

    $query = $this->db->get($this->table_name);
    return $query->num_rows() == 0;
}

now I want to use jquery to do some ajax checking by using the post method. I want to know the best way to do this..

should I create a new function in controller to check if the user name is available or not ? please tell me ,to which url jquery has to make post request..

<script type="text/javascript">
$(document).ready(function()
{

$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");

if(username.length > 3)
{
$("#status").html('<img src="images/loader.gif">&nbsp;Checking availability.');

$.ajax({
type: "POST",
url: "/index.php/auth/user_availability",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){

if(msg == 'OK')
{

$("#username").removeClass("red"); 
$("#username").addClass("green");
msgbox.html('<img src="yes.png"> <font color="Green"> Available </font>');
}
else
{

$("#username").removeClass("green"); 
$("#username").addClass("red"); 
msgbox.html(msg);
}
});
}
});

}
else
{

$("#username").addClass("red"); 
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
</script>

Thanks !

3
  • What is the actual question? Do you have an error? Are you using FireBug? FireBug will help you debug/resolve any AJAX problem: getfirebug.com Commented Mar 22, 2011 at 8:18
  • I want to know if I can use the function in helper directly without writing a new function which does the same in controller.and how to pass the parameter to the function in helper/controller using jquery.. Thanks ! Commented Mar 22, 2011 at 8:35
  • You cannot access a helper directly from the URL no, that is the job for a controller wether it is AJAX or not. AJAX is no different to a normal HTTP request called from the browser. Commented Mar 22, 2011 at 11:39

2 Answers 2

4

What I tend to do is create a controller named ajax which basically holds all my ajax related functions. This way I will always now where to point my ajax calls:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax extends CI_Controller {

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

    public function index()
    {
        $this->output->set_output("This is an AJAX endpoint!");
    }

    public function user_availability()
    {
        $this->load->model("users");
        $res = $this->users->is_username_available( $this->input->post("username") );
        if( $res )
            $this->output->set_output("OK");
        else    
            $this->output->set_output("NOT OK");
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/ajax.php */

When this controller has been made you can always create more ajax calls if you need any and they are all at the same place.

Your jQuery ajax call then needs to changed to something like:

...
$.ajax({
type: "POST",
url: "/index.php/ajax/user_availability",
data: "username="+ username,
---

I hope this gives you an idea to a solution.

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

Comments

0

You may make an Ajax request to the page on the server to check if user name is available, this can be possible even without using JQuery, instead use plain JavaScript and XMLHttpRequest object, since all modern browsers support Ajax. You can request this page on certain event, i.e. when user is typing in his/her name in the text box, or when textbox loses focus when typing of name is done, etc.

The method that will request the availability of name in database from the server will be as follows. Purely with JavaScript and Ajax. (Note that in the sample method, I have used JSP page and intead of POST, I have used GET method, since the data to be requested is not sensitive hence can be called without any encryption)

function requestUserInfo(x)
{
    var url = "./CheckAvailability.jsp?id=";
    var xhr = false;
    if(window.XMLHttpRequest) //Standard object that works with every browser except for IE
    {
        xhr = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) //Use IE specific object if IE is the browser
    {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    function handleHttpResponse()
    {
        var results=xhr.responseText; //Store the response received from CheckAvailability.jsp
        if(results.trim()=="0") //The CheckAvailability.jsp page will return 0 is user name exists
        {
                //Your code to perform something if user name exists
        }
        else
        {
                //Your code to perform something if user name does not exist
        }
    }
    var sId = x.value;
    xhr.open("GET", url + escape(sId), true);
    xhr.onreadystatechange = handleHttpResponse;
    xhr.send(null);
}

The method requestUserInfo(x) accepts the reference of the control in which we'll be calling this method and will request the following page CheckAvailability.jsp

<%@ page import="java.sql.*" import="java.io.*" import="java.util.*" %>
//The following code checks for User name existence in a table stored in MySQL
<% 
try
{

        Class.forName("com.mysql.jdbc.Driver");
        Connection cn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/MyDatabase?user=;password=","myuser","mypass");
        Statement st=cn.createStatement();
        String user=request.getParameter("id");
        ResultSet rs=st.executeQuery("select * from users where usernm='"+user+"'");
        if(rs.next()) //Check if User Already Exists
        {
            //Return "0" if Exists
            out.print("0");
        }
        else
        {
            //Return "1" if User name does not exist
            out.print("1");
        }
        st.close();
        cn.close();

}   
catch(Exception e)
{
    out.println(e);
}
%>

4 Comments

If he is using PHP and COdeIgniter, why on earth would he want to use Java for something so basic?
@Phil Sturgeon: I haven't used CodeIgniter but this method works with any framework used to create dynamic site, without relying on JQuery, except if developer has put some restrictions, like Krishna mentioned that query strings are disabled.
Right, but in what world does "just throw in some JSP to your JS/PHP" website seem like the easiest option?
@Phil Sturgeon: Example I gave above shows how I worked with JSP to perform the same, I don't force to use JSP, as one can call PHP page as well, and get results whether user name exists or not. And I have even mentioned in the note that the example I've showed uses JSP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.