0

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.

JavaScript

<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize(); 
     $.ajax({  
 type: 'POST', url: 'secure/check_login.php',  dataType: "json",  data: { username: username, password: password,  },
    datatype:"json",
            success: function(result) {                 
               if (result.success != true){
                   alert("ERROR");
                   }
                   else
                   {
                       alert("SUCCESS");
                   }
            }   
    });  
} 
</script>

PHP

$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
    $password = encryptPassword($password);
    if (getUser($username,$password) == 1)
    {
       refreshUID($session_id);
        $data = array("success" => true);
        echo json_encode($data);
    }
    else
    {
        $data = array("success" => false);
        echo json_encode($data);
    }
}
function refreshUID($session_id)
{
    #Update User Session To Database
    session_start($session_id);
}
function encryptPassword($password)
{
    $password = $encyPass = md5($password);
    return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
    return 1;
}
else 
{
    return 0;;
}
}
?>

I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.

Rich Adams
  • 26,096
  • 4
  • 39
  • 62
  • How are you going about this on the back-end? Using json_encode(...)? What does your current JSON data look like? – David Harris Dec 25 '12 at 04:25
  • 2
    Please, don't use `mysql_*` functions to write new code. They are no longer maintained and the community has begun [deprecation process](http://goo.gl/KJveJ). See the *[red box](http://goo.gl/GPmFd)*? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide which, [this article](http://goo.gl/3gqF9) will help you. If you pick PDO, [here is good tutorial](http://goo.gl/vFWnC). – Waleed Khan Dec 25 '12 at 04:26
  • @DavidHarris Did you mean this part within the php? `if (getUser($username,$password) == 1) { refreshUID($session_id); $data = array("success" => true); echo json_encode($data); } else { $data = array("success" => false); echo json_encode($data); } ` I'm trying to communicate to the jQuery retrieving it by telling it whether the post worked or not. – Oliver K Dec 25 '12 at 04:29
  • Well that's all correct, so I'd assume it's an issue with the front-end. I've never seen someone parse JSON like that in jQuery, so it's probably what redwind said below, it may expect a certain data-type from the server. – David Harris Dec 25 '12 at 04:31
  • You can check this too; => "if ($count = 1)". This will return alltimes true!. But this is only a another problem... – mr_app Dec 25 '12 at 04:35

4 Answers4

2

There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.

No data returned would mean result.success doesn't exist...which is likely the error you see.

First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless

You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.

to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly

dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase

Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.

Also inspecting request you would likely see no json was returned

EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

Try to add this in back-end process:

header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');

hope this help !

redwind
  • 161
  • 1
  • 13
  • Unfortunately it did not help :/ – Oliver K Dec 25 '12 at 04:34
  • 1
    Can you post the answer from the json_call? You can read it in the console after firing your postevent. – mr_app Dec 25 '12 at 04:37
  • As mr_app said above, use network tab of firebug on firefox or develope tool on chrome (F12) to check your request and respone type :) – redwind Dec 25 '12 at 04:42
  • TypeError: Cannot read property 'success' of null [http://www.olimoli-web.com/projects/Web/Scripts/php/seoManager/login:89] Is that what you meant? By the way, feel free to browse that page. Its where my script is located. – Oliver K Dec 25 '12 at 04:43
  • it cause by you trying access a json object `result.success` but server's respone is not a json object. develope tool on browser will help you see your request and server's respone – redwind Dec 25 '12 at 04:46
0

i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong! You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"

So you have to select it this way

$('#inputUsername').val();
// or
$('input[name="username"]').val();

I tried it again. You PHP script is responsing nothing. Just a 200.

$.ajax({
type: 'POST', 
url: 'secure/check_login.php', 
dataType: "json", 
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(), 
success: function(result) {
    if (result.success != true){
        alert("ERROR");
    } else {
        alert("HEHEHE");
    }
}

});

Try to add following code on the top of your PHP script.

    header("Content-type: appliation/json");
    echo '{"success":true}';
    exit;
mr_app
  • 1,292
  • 2
  • 16
  • 37
0

You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

Community
  • 1
  • 1
Guilherme
  • 1,980
  • 22
  • 23