Jump to content

Ajax log on handler wrapping redirected to page in response content


Go to solution Solved by Barand,

Recommended Posts

I have a log on page that is being handled with ajax and going to a php function.

The php function returns some text if the log on is not successful - this is being put into an alert that shows on the page.

If the log in is successful there is a header to redirect to the logged in page.

The issue is that when logging in successfully, the html that wrapped the error messages is now wrapping the whole logged on page that i am rediurected to.

This is the script

<script>
		$('#login').click(function() {
			$em = $('#email').val();
			$pw = $('#password').val();
			$.ajax({

				type: 'post',
				data: {
					'ajax': 'login',
					'email': $em,
					'pass': $pw

				},
				success: function(resp) {
					if(resp != 'success'){
						$('.alert-container').append("<div class='row alert alert-warning text-center'><span class='text-center'>"+resp+"</span></div>")
						
					}
					

				}
			})
		})
	</script>

and this is the php - i added the return success to try and avoid this but it has been unsuccesful in remedying my issue.

function login($email, $pass){
    include 'includes/dbconn.php';
    $sql = "SELECT pass, id, banned from user where email = :email";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':email' => $email
    ]);
    if ($stmt->rowCount() != 1) {
        return "This is a problem with your account, please email the administrator.";
    } else {
        $row = $stmt->fetch();
        if (password_verify($pass, $row['pass'])) {
            $_SESSION['userId'] = $row['id'];
            header('Location: home.php');
            return "success";
        } else {
            return "Your username and password combination do not match.";
        }
    }
}

 

  • Solution

When you send an ajax request to a page, all output then goes into the response that is returned. (ie what you would see if you called that page in your browser is the reponse (which you can use to your advantage to test ajax responders).

Remove the location header from the responder code and do the redirect in the calling page when you receive a succesful response.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.