如何在PHP中使用return获取响应并在jquery中使用它

时间:2012-04-11 13:06:35

标签: php jquery

以下jquery用于检查数据库中是否有用户名和电子邮件。当我回显false或ture时,jquery可以工作,但它会给出PHP错误。所以我只想从PHP代码中返回false或true。但是当我这样做时,jquery不起作用。

我在这里做错了什么?

提前致谢。

Jquery的

$(document).ready(function(){
$("#name").blur(function()
{
    var nameval = $(this).val();
    if(nameval)
    {
        ...
        ...
        //check the username exists or not from ajax
        $.post("<?php echo site_url('welcome/user_availability'); ?>",{ what:$(this).val(), where:"name" } ,function(data)
        {   
            if(data==false) //if username not avaiable
            {
                $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                {
                //add message and change the class of the box and start fading
                $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });
            }
            else
            {
                $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
                {
                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
                });
            }

        });
    } 
    else
    {
        $("#msgbox").fadeTo(200,0);
    }       
});
 ...
 ...

PHP

function user_availability()
{
    $module = "subscribers";
    $where = $this->input->post('where');
    $what = $this->input->post('what');
    $customers = $this->MKaimonokago->getAllSimple($module, $where , $what );
    if (!empty($customers))
    {
     //user name is not available
        return false; // I want to use return here.
       // this works but it gives php error
       // echo "false";
    }
    else
    {
        return true;
    }    
}

PHP错误

ERROR - 2012-04-11 21:43:06 --> Severity: Warning  --> Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/kaimonokago2.0/application/modules/welcome/controllers/welcome.php:1084) /Applications/MAMP/htdocs/kaimonokago2.0/system/core/Output.php 391

2 个答案:

答案 0 :(得分:1)

尝试:

// in php
echo(json_encode(TRUE));

答案 1 :(得分:1)

您描述的错误与HTTP标头有关。当您尝试在第一个echo语句后调用header()session_start()setcookie()时,通常会出现此错误。请注意,<?php标记前面的空行也会打印换行符。

您无法使用return语句打印某些内容,您应该使用返回值echoprint()