views:

34

answers:

3

I've built a function for checking a username. I'm using it as a callback for form validation in CodeIgniter, and it works nicely. However, I'd like to also use it with AJAX to check on the fly if the user has JS enabled. So my controller has this:

function check_username($s = FALSE)
{
    if ($s):
        $this->db_common->like('username', $s);
        $query = $this->db_common->get('users');

        if ($query->num_rows() > 0):
            $this->form_validation->set_message('check_username', 'Username taken. Choose another!');
            return FALSE;
        else:
            return TRUE;
        endif;
    else:
        echo 'Username required';
    endif;
}

And my HTML/JS is this:

$(document).ready(function()
{
var delayed;
$("#username").keyup(function()
{
    clearTimeout(delayed);
    var value = this.value;
    if (value)
    {
        delayed = setTimeout(function() {
            $.ajax
            ({
                type: "POST",
                url: "<?php echo base_url(); ?>auth/check_username/",
                data: $("#username").val(),
                success: function(html)
                {
                    $("#username_check").html(html);
                }
            });
        }, 100);
    }
});
});

Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that? Basically, I want jQuery to check if it's false, then say 'username exists' and if it's true, then 'username is okay'.

A: 

Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that?

You can't directly. I would output 0 or 1 instead.

Pekka
+1  A: 

I would return true or false as JSON boolean from your PHP script and use javascript's eval() function to evaluate that to a javascript var.

Josiah
The problem is that I need to keep TRUE and FALSE in there for my CodeIgniter Form Validation callback to function properly. It's required.
dallen
Ah... well if it only contains the text TRUE or FALSE, I guess you could do "if (html == "TRUE") return true; else return false;
Josiah
+1  A: 

Do something like the following:

echo 'ok';
return TRUE;

The reason for this is that jQuery can't see the boolean values returned by PHP as they're not send to the browser's output.

Yorick Peterse