Skip to content
Advertisement

why am I not redirected after a ajax post?

I’m using a page (file1.php) to submit a specific number to another php file (file2.php) this second PHP file as to take data from a database and extract information then return it to file1.php, here is file2.php

<?php
require('../model/encapsulation.php');
require('../model/connection.php');
require('../model/bunchofmethod.php');
if (isset($_POST['SpecificNumber'])) {
    $NS = $_POST['SpecificNumber'];
    $info = execRequest::folderInfoFromNS($NS, $dbh);
    $name = $info['name'];
    $firstName = $info['firstName'];
    $UID = $info['UID'];
    $idFound = json_encode(array($name, $firstName, $UID));
}
?>
<!DOCTYPE HTML>
<html lang="fr">
<head>
    <script src="../JS/jquery-3.4.1.min.js"></script>
    <?php
    if (isset($idFound)){
        ?>
        <script>
        $(document).ready(function () {
            $.post("../view/file1.php",
                {
                    idFound: <?php echo $idFound?>,
                    searchDone: 1
                });
        })
    </script>
    <?php
    }
    ?>
</head>
</html>

when I submit a specific number with file1 (it is only a regular form and a php part which vardump $_POST['idFound'] if it is set) I’m redirected to file2 but not redirected again to file1 , why ?

Advertisement

Answer

I think you may have misunderstood the process here.

If you want file1 to make a request to file2, and file2 to send a response, then it makes no sense to write code in file2 which makes an AJAX request to file1. You don’t need a new request to file1 (because that creates a new call to a new instance of file1’s script). What you need is simply for file2 to provide a response to the request coming from the original instance of file1.

So if you want file2 to respond and return the JSON data to file1, then simply echo it:

$idFound = json_encode(array($name, $firstName, $UID));
echo $idFound;

(And get rid of all the HTML and jQuery code).

The echoed data will then be returned as the response to file1’s request.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement