0

I would just like to know how to go about comparing the resulting echo from a $.ajax call in JavaScript. I attempted this and even though I get 1, it doesn't actually compare the results correctly.

jQuery:

        $.ajax({
        type: "POST",
        url: "login.php",
        data: user,
        dataType: 'html',
        success: function(result)
        {
            alert(result);
            if(result == '1')
            {
                alert("logged in :D");
                //document.location.replace('home.php');
            }
            else
            {
                alert("not logged in :<");
            }
        },
        failure: function()
        {
            alert('An Error has occured, please try again.');
        }
    });

PHP:

<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);


if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

$json = $_REQUEST['json'];
$json = stripslashes($json);

$jsonobj = json_decode($json);

$password = $jsonobj->password;
$email = $jsonobj->email;

mysql_select_db("tinyspace", $con);

$result = mysql_query("SELECT 1 FROM users WHERE email = '"
                    . $email . "' AND password = '" . $password . "'");

 while($info = mysql_fetch_array( $result )) 
 { 
    if($info[0] == 1)
    {
        echo '1';
    }
}
 ?> 
pimvdb
  • 146,912
  • 75
  • 297
  • 349
Crossman
  • 258
  • 4
  • 18

2 Answers2

0

There's probably a space or line break after the '1' that is echoed. Check if there's no space before the opening <?php tag and remove the closing ?> tag (you're allowed to do that, and it will prevent accidental whitespace being outputted.

You should be able to check by changing the javascript to:

alert('X' + result + 'X');

You'll see soon enough if there's any whitespace around result.

GolezTrol
  • 111,943
  • 16
  • 178
  • 202
0

try to send json response

php:

echo json_encode(array(
    'status' => 'ok',
));

js:

dataType : "json",
success : function(response) {
    if (response.status == "ok") {
        alert('success');
    } else {
        alert('error');
    }
}
ladamalina
  • 66
  • 2