开发者

jQuery.ajax / CodeIgniter (PHP) : Returning TRUE/FALSE in PHP, how can I get jQuery to see this?

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):
   开发者_C百科     $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'.


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.


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.


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.


There is a way to do it with PHP and jQuery. Here is an example...

simply have your php script echo back true or false.

PHP-> echo true; or echo false;

$.post("your_url/your_class/your_method", {  } ,
function(data) {

    if(data) alert('true');
    else alert('false');

}, "json")
.error(function() { //alert("an AJAX error occurred!"); 
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜