简体   繁体   中英

Webpage wrongfully reloads on javascript close

Trying to create a webpage with a dynamic selection of model numbers based on the selection of a manufacturer, using just php mysql queries (ie no jQuery or AJAX). The user would select a manufacturer, a form would submit, and the webpage would reload with all user inputs and a newly populated selection field for model numbers.

I have 2 forms, a main visible one where all inputs are required for my mysql database, and a hidden one that can be submitted with partial inputs. The only purpose of the hidden one is to submit the manufacturer and maintain all other inputs the user has provided on the page.

<form id="partialnew" action="page.php" method="post">
    <input id="partialnewmodel" name="partialnewmodel" type="hidden">
    ... other similar inputs ...
</form>

<form id="new" action="page.php" method="post">
    <select id="newmanufacturer" name="newmanufacturer" onchange=populatemodels() form="partialnew">
        <option value="">-</option>
        <?php
            ... populated from mysql query ...
        ?>
    </select>

    <select id="newmodel" name="newmodel" required>
    </select>
    ... other inputs ...
</form>

The manufacturer input is in the main form so it appears correctly on the page, but it is linked to the partial form so it can be submitted without the other required inputs.

OnChange of the manufacturer, I copy all my main form inputs to the hidden form, and call form.submit() on that partial form. When the page reloads, I query my database for model numbers based on the selected manufacturer. Then I load the maintained values into javascript using echo.

echo "<script>
        var manufacturer = '';
        var model = '';
        ... other variables ...
";

if (isset($_POST['newmanufacturer']) && $_POST['newmanufacturer'])
{
    echo "manufacturer = '{$_POST['newmanufacturer']}';";
}

if (isset($_POST['partialnewmodel']) && $_POST['partialnewmodel'])
{
    echo "model = '{$_POST['partialnewmodel']}';";
}

... load other inputs into javascript ...

echo "</script>";    // <--- After this command, the webpage reloads

I don't know why, but after the script is closed with that last echo, the page reloads. I have added print statements and console logs before and after that echo, and it only returns those before. I have tried adding a window.stop() command to prevent it from immediately reloading, but it didn't look like anything was amiss when I inspected the resulting webpage.

When it reloads, it purges all of my posted inputs and returns the webpage to its default state.

EDIT I just moved my php code to a different file, and pointed the hidden form action to the new file. Here is the entire new file.

<?php
    session_start();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Muh Webpage</title>
    <link rel="stylesheet" href="../css/index.css">
    <link rel="icon" href="../images/favicon.svg" sizes="any" type="image/svg+xml">
</head>

<body>
    <?php
        $_POST = filter_var_array($_POST, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);

        $mysqli = new mysqli('**********', '**********', '**********', '**********');

        if ( $mysqli->connect_error ) {
            die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
        }

        if (empty($_POST))
        {
            echo "<p>POST is empty</p>";
        }
        else
        {
            foreach ($_POST as $key => $value)
            {
                echo "<p>" . $key . " - " . $value . "</p>";
            }
        }

        if (isset($_POST['newmanufacturer']))
        {
            echo "<p>start of newmanufacturer handling</p>";
            $sql = "SELECT Model
                    FROM Models
                    WHERE ManufacturerName='{$mysqli->real_escape_string($_POST['newmanufacturer'])}'
                    ORDER BY Model;";
            $result = $mysqli->query($sql);

            if ($result)
            {
                $models = array();
                $i = 0;

                while ($row = $result->fetch_array())
                {
                    $models[$i] = $row['Model'];
                    $i = $i + 1;
                }

                $_SESSION['Model'] = $models;
            }
            else
            {
                echo '<p style="color: red;">ERROR ' . $mysqli->errno . ': MySQL error description=' . $mysqli->error . '</p>';
            }

            echo "<p>before scripting in newmanufacturer handling</p>";

            echo "<script>
                var location = '';
                var description = '';
                var manufacturer = '';
                var model = '';
                var serialnumber = '';
                var additionalinfo = '';
            ";
            if (isset($_POST['partialnewlocation']) && $_POST['partialnewlocation'])
            {
                echo "location = '{$_POST['partialnewlocation']}';";
            }
            if (isset($_POST['partialnewdescription']) && $_POST['partialnewdescription'])
            {
                echo "description = '{$_POST['partialnewdescription']}';";
            }
            if (isset($_POST['newmanufacturer']) && $_POST['newmanufacturer'])
            {
                echo "console.log('manufacturer loading into js');";
                echo "manufacturer = '{$_POST['newmanufacturer']}';";
            }
            if (isset($_POST['partialnewmodel']) && $_POST['partialnewmodel'])
            {
                echo "console.log('model loading into js');";
                echo "model = '{$_POST['partialnewmodel']}';";
            }
            if (isset($_POST['partialnewserialnumber']) && $_POST['partialnewserialnumber'])
            {
                echo "serialnumber = '{$_POST['partialnewserialnumber']}';";
            }
            if (isset($_POST['partialnewadditionalinfo']) && $_POST['partialnewadditionalinfo'])
            {
                echo "additionalinfo = '{$_POST['partialnewadditionalinfo']}';";
            }
            echo "console.log('done loading into js');";
            // echo "window.stop();";
            echo "</script>";
            
            echo "<script>
                console.log('never reach here');
                window.stop(); 
            </script>";
            echo "<p>Never reach here neither</p>";
        }
    ?>
</body>
</html>

This new file has the same problem. Unless I uncomment the window.stop() line, it will immediately reload. There is nothing else at all in this file.

var location='';

is the problem. Because it's not inside a function or otherwise scoped, this is effectively an alias for window.location (since window is the default object in browser-based JS). And setting that value is an instruction to the browser to navigate to the page specified in that value. (If you set an empty string as in this example, it will navigate to the current URL again.)

Here's a proof of concept showing this behaviour: https://jsfiddle.net/k4tanxd2/

You just need to name the variable something else, eg:

var loc = '';

(Or of course you can take a different design approach which doesn't involve creating lots of global variables.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM