0

I have a html code which sends the input to the PHP where the php redirect to a login page.

But when i do the post request as bellow, it gives a response back to the javascript; with the forwarding index.html code without redirect to the index.html.

<script>
        function Sendmeaway() {
            var item_i = document.getElementById("item_select").value;

            if (item_i == "Initial_Value") {
                alert("Please Select the Correct Option or Enter the Comment");
            } else {
                $.post("./back_p/add_change_req.php", {
                        item : item_i
                    },
                    function(data, textStatus) {
                        alert("Response from server: " + data);
                        document.getElementById("item_select").selectedIndex = 0;
                        location.reload();
                    });
            }

        };
    </script>

PHP code (it works fine when i go directly to the php)

<?php echo $_POST["item"]; header('location: ../index.html'); ?>

checkmate
  • 267
  • 2
  • 6
  • 19

3 Answers3

1

You can't redirect users like that. AJAX calls can only send and recieve data.

Instead redirect the user using window.location.href = '' in the success function of your AJAX call.

So instead of

<?php echo $_POST["item"]; header('location: ../index.html'); ?>

Do

<?php echo $_POST["item"]; return '../index.html'; ?>

Then use that returned value inside your script like:

function(data, textStatus) {
    alert("Response from server: " + data);
    document.getElementById("item_select").selectedIndex = 0;

    window.location.href = data; 
});
Red
  • 6,599
  • 9
  • 43
  • 85
0

When you make an ajax call you need to change the page on javascript side like that. You can send 0 or 1 from php to decide redirecting or not.

kylngr
  • 61
  • 8
0

Instead of using php header, use a <meta> tag outside the PHP tag

Such as:

<?php

echo($_POST["item"]);

?>

<meta http-equiv="refresh" content="5;URL='../Index.html'" />

replacing the 5 after content=" to however many seconds you want until the redirect executes