Ajax post成功函数返回成功和错误

时间:2013-04-12 07:06:48

标签: php javascript ajax jquery

好吧所以我试图让ajax发布到我的php文件,查找一个mysql字段,如果它存在,则回显'clientsuccess'否则回显'客户端已经存在' 但是在成功函数上它返回两个值,尽管它们在php if语句中。 我很可能会错过一些非常简单的东西,但是非常感谢任何帮助。

PHP:

    <?php 
session_start();
$clientArray = $_POST['clientArray'];

$clientArray = explode(',', $clientArray);
$count = 0;


foreach($clientArray as $clientField) 
{

trim($clientField);
if(empty($clientField)) {
$clientField = '-'; 
}

}




$con = mysql_connect("localhost",$_SESSION['MysqlUser'],$_SESSION['MysqlPass']);
if (!$con)
{
die('Could not connect with '.$_SESSION['MysqlUser'].mysql_error());
}

mysql_select_db("smeinsti_SPW_Inventory", $con);

$checkclient = mysql_query("SELECT ClientName FROM Clients WHERE ClientName = '".$clientArray[0]."'", $con);

if(mysql_num_rows($checkclient)==0)
{

$sql="INSERT INTO Clients (`ClientName`, `PhoneNumber`, `Email`, `Address`, `OrderDate`)
VALUES
('$clientArray[0]', '$clientArray[1]', '$clientArray[2]', '$clientArray[3]', CURDATE())";


$clientArray[0] = $_SESSION['ClientName'];
echo "clientsuccess";



} else {
echo 'Client already exists';   
}


?>

JS:

    function NextPage()
{
var ClientData = [];

$('form#order-form.create input[type=text]').each(function() {

ClientData += $(this).val() + ',';

})

alert(ClientData);

var parameters = {
clientArray: ClientData
};

$.ajax({
type: "POST",
async:false,
url: "write_client.php",
data: parameters,
success: function(result){       
var res=result;
if(res = 'clientsuccess') {
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
}
}); 







}

2 个答案:

答案 0 :(得分:1)

您的情况等号不正确!把'=='

    if(res == 'clientsuccess') { //Double Equal to
    window.location = 'admin.php?id=7';
    } else {
    alert('Client already exists');
    }

答案 1 :(得分:0)

mysql_num_rows返回所选行的数量,而不是某行的字段。使用mysql_fetch_row获取您使用查询选择的行:

您还可以使用mysql_result获取行并获取某个字段:

$ client exist = mysql_result($ checkclient,0,0); 这将获取第一行(基于零)并返回第一个字段(基于零)。