0

So I have discovered a method of transferring a JavaScript variable over to PHP (shown below):

<form name="submitForm" action="display2.php" method="post">
        <input type="text" name="myValueResult" id="myValueResult" value="">
</form>

<?php
        $result = $_POST['myValueResult'];
        echo "<script>alert($result)</script>";
?>

<script>
        let myValue = localStorage.getItem('Key'); (//This value came from a different page)
        document.getElementById('myValueResult').value = myValue;

        function something() {
            document.submitForm.submit();
        }

        something()
</script>

Sorry if this method seems bad, I am not experienced with coding. But anyway PHP always gets to finish first which is not allowing JavaScript enough time to change the form input to it's variable value and is why PHP keeps alerting a blank number the first time but afterward it alerts the correct number but keeps looping the webpage.

Any feedback would be very much appreciated.

OddsOver1
  • 13
  • 5
  • 2
    [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – ADyson Nov 07 '22 at 11:13
  • 1
    [Checking if form has been submitted - PHP](https://stackoverflow.com/questions/7711466/checking-if-form-has-been-submitted-php) - the reason it shows a blank number the first time is because you're not telling PHP to detect whether the browser had submitted the data before trying to use it. You can't switch the order in which PHP and JS run - PHP is used on the server to build your page and provide a response to the browser's requests. It then returns a page to the browser, which can then run any JavaScript contained within it. – ADyson Nov 07 '22 at 11:14
  • Remember: the web is a stateless, disconnected, client-server architecture. When the browser makes a HTTP request to the server, it starts the PHP code running. When the PHP code stops running, the finished output is delivered to the browser as the next page. To make the server do something more after that, you need to send another HTTP request to the server to start the process again. To trigger that, you can use AJAX (to avoid refreshing the whole page), or submit a form containing data, or cause a navigation (via a hyperlink or Javascript) to a new URL which may include query parameters. – ADyson Nov 07 '22 at 11:17
  • Thank you so much, I managed to find a solution using the "Checking if form has been submitted - PHP" link you sent. – OddsOver1 Nov 07 '22 at 11:25
  • `keeps looping the webpage`...yes, because every time you load the page you tell it to run `something()`, which then submits the form automatically. – ADyson Nov 07 '22 at 11:25

0 Answers0