user2905416 user2905416 - 1 month ago 5
Ajax Question

header() in php is not working

i'm very new in PHP and please don't mark this question as duplicate, because I've searched and found many solutions on stackoverflow as well as other sites, here is the code in my login.php what I'm trying to do is pass some data to controller.php:

window.onload = function(){
$('#btnLogin').click(function() {
var val1 = $('#txtusername').val();
var val2 = $('#txtpassword').val();
var val3 = "login";
$.ajax({
type: 'POST',
url: 'controller.php',
data: { action: val3, username: val1, password: val2 },
success: function(response) {
alert(response);
}
});
});
}


It is working well if I don't want to navigate to another page "index.php" because in controller.php I've received all data what passed from login.php, but the header("Location: index.php") is not working.Bellow is my controller.php:

<?php
header("Location: index.php");
exit();
?>


I've tried some solutions like: "delete blank spaces",add "error_reporting(E_ALL)" and "ini_set('display_errors', 'On') " and "ob_start()" to the top of the controller.php file, but nothing better happen.

Answer

You can't do that via ajax request. If you want to navigate to index.php after you finish processing data via controller.php use jquery redirection inside your success response.

success: function(response) {
    window.location.replace("index.php");   
}
Comments