1
votes

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.

2
Is there any whitespace before the opening <?php tag, or is there any output coming from other files before you include that "controller" file? If so: headers are already sent, so you can't set them. Also: if a file contains only PHP code, it's recommended you omit the closing ?> tag - Elias Van Ootegem
Are you trying to redirect using an ajax call? - Jeff Puckett
You have to use window.location.replace("your_url"); in your JavaScript - Khaled
Elias Van Ootegem: thanks, there is no whitespace before the opening <?php tag and there is no output coming from other files before I include that "controller" file and I sent nothing to other page before I call the header(); - user2905416
Khaled: could you please explain your answer in more details? - user2905416

2 Answers

2
votes

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");   
}
0
votes

You are doing your redirect in ajax request. This will not redirect your page, it will only redirect the ajax request. Instead return some json response and check this response in the ajax callback and then redirect the user using javascript.