E.Sophia E.Sophia - 6 months ago 18
PHP Question

PHP redirect not changing the page

I have three different parts to my page. The first is a button, the second is a JS function (AJAX request) and the last one is a PHP script that is called by the AJAX request.

The PHP script is supposed to call a web service to process the data. Here is the content of the PHP script:



<?php
if(isset($_POST['forminfos'])){

$client = new SoapClient('URL');
$client->Function();
header('Location: localhost/page.php');
}
?>





The page is not redirected but when I check the console I can see that there is a GET with the localhost/page.php content.

enter image description here



//on button sumbit
var data=$('#forminfos').serializeArray();
$.ajax({
url: '../func.php',
data:data,
type: 'POST',
dataType: 'json',
success: function () {

},
error: function(){

}
});





I expected the page with the AJAX request to be redirected to 'localhost/page.php' but it is not.

Answer

The problem is that the file you are doing the redirect in is being called by AJAX. That means that although you are redirecting that request page, the actual page you made the ajax request from is not being redirected. The end of your ajax request results in the script you called being redirect not the page it is requested on.

If you only goal is to get to your destination in the header (localhost/page.php) then you could wait for the AJAX request to finish and do:

window.location.href = "localhost/page.php"

This uses javascript instead to redirect the page on the successful completion of your AJAX request.


Further reading:

Basic JS docs about window

Difference between window location and window replace