简体   繁体   中英

Ajax for login check not working and submitting form

I know there are many answers about my problem but I'm new to ajax and javascript I would like someone to point me to the problem causing my script to fail.
I made login check with ajax based on this answer Check if user logged in on ajax page change . When the submit button is clicked the function checks if the user is logged in or not. I want to display an alert if its not and to proceed to next page if it is.
My javascript:

    $('#bookForm').submit(function(){
    $.ajax({
            url : '<?=BASE_URL?>user/logged.php',
            success : function(response){
                if (response.logged == true) {
                    return true;
                }else{
                    alert('you need to log in');
                    //e.preventDefault();
                    return false;
                }
            }
    });
});  

My php script that checks if the user is logged:

$response = array();

if(!isset($_SESSION['userId'])) {

    $response['logged'] = false; 

}else{

    $response['logged'] = true;

}

$response = json_encode($response);

echo($response);

I'm new to javascript/ajax and I'm not sure where the problem is. The function returns the alert for not logged in user despite the user being logged in.

You have to add this option : dataType:'json' in your ajax call.

And echo json_encode($response); without any return.

Make following changes in your Jquery code.

$('#bookForm').submit(function(event){

event.preventdefault();

    $.ajax({

        url : '<?= BASE_URL ?>user/logged.php',
        dataType:'json'
        success : function(response){

            if (response.logged == true) {
                return true;
            } 
            else{
                alert('you need to log in');
                //e.preventDefault();
                return false;
            }
        }
    });
});

Remove the return json_encode($response); from php script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM