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.

5
  • How are you going about this on the back-end? Using json_encode(...)? What does your current JSON data look like? Commented Dec 25, 2012 at 4:25
  • 2
    Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information. Commented Dec 25, 2012 at 4: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. Commented Dec 25, 2012 at 4: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. Commented Dec 25, 2012 at 4:31
  • You can check this too; => "if ($count = 1)". This will return alltimes true!. But this is only a another problem... Commented Dec 25, 2012 at 4:35

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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 !

5 Comments

Unfortunately it did not help :/
Can you post the answer from the json_call? You can read it in the console after firing your postevent.
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 :)
TypeError: Cannot read property 'success' of null [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.
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
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;

3 Comments

isn't that what I posted 20 minutes ago with a lot more detail? Your first selector is also invalid....no # prefix for tagName
"inputUsername" is the ID he is using for the input field.
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.