user2273253
user2273253

Reputation: 1

Ajax post success function returning both success and error

Okay so I am trying to get ajax to post to my php file, lookup a mysql field and if it exists echo 'clientsuccess' otherwise echo 'Client already exists' but on success function it returns both values despite the fact that they're in an php if statement. I am quite possibly missing something incredibly simply, but any help is greatly appreciated.

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');
}
}
}); 







}

Upvotes: 0

Views: 196

Answers (2)

liyakat
liyakat

Reputation: 11853

mysql_num_rows returns the number of selected rows and not the fields of a certain row. Use mysql_fetch_row to fetch the row you have selected with your query:

You could also use mysql_result to fetch a row and get a certain field:

$client exist = mysql_result($checkclient, 0, 0); This fetches the first row (zero based) and returns the first field (zero based).

Upvotes: 0

Jenson M John
Jenson M John

Reputation: 5699

Your condition Equal symbol is not correct! Put '=='

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

Upvotes: 1

Related Questions