Can you get your PHP "POST" code to run before your Javascript?

I would like to be able to display an Alert based on data I get out of my POST event.

Here is a simplified example of what I am trying to do.

/* I want the order of events to be:
   1.  User types in a letter
   2.  User clicks the button
   3.  My PHP code for the POST event sets a variable ($fruit), based on the user input.
   4.  The HTML code checks for the existence of the variable ($fruit) and writes it to another input element.
   5.  The Javascript opens an Alert displaying the contents of the "fruit" input.
 */

Here is the Javascript code:

$(document).ready(function() {

  // show a dialog box when clicking on a link
  window.onsubmit = function (e) {
  e.preventDefault();

    alert( ("#fruit").val() );
  };

});

Here is the .php file:

<!DOCTYPE html>
<html lang="en">

<header>
	<h1>Testing</h1>
</header>

<body>

	<?php
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		
		$user_input = trim($_POST["letter"]);

		if ($user_input == 'A') {
			$fruit = "apples";
		} elseif ($user_input == 'B') {
			$fruit = "bananas";
		} else {
			$fruit = "No fruit for you!";
		}
	}
	?>

	<form id="form_to_submit" action="index.php" method="POST">

		<fieldset>

    		<label>Type A for apples and B for bananas:</label>
		<input type="text" name="letter" id="letter"> 
		<input type="text" name="fruit" id="fruit" value="<?php if(isset($fruit)) {echo $fruit;} ?>"> 
		<button type="submit" id="click">Click Here to see your fruit selection.</button>

		</fieldset>

	</form>

<!-- Link to jQuery file so any plug-ins can work 
Including the production version here.  Can also download one for better debugging.  -->
<script type="text/javascript" src="jquery-1.12.0.min.js"></script>

<!-- Link to My Javascript code -->
<script type="text/javascript" src="myTestScripts.js"></script>

</body> 
</html>

You can totally do that by making an XHR request where you submit the form data without causing your page to reload. Have you done something like that before? :slight_smile:

It should be noted kirupa’s suggestion requires taking the PHP out of the HTML page and placing it in a separate file that is loaded and read by JavaScript in a separate request.

In-HTML PHP is processed before the page is fed to the browser - before the HTML renders. It happens on the server when the page is first requested. Then the rendered HTML, sans PHP (with whatever non-PHP text the code left behind) is passed down the wire into the browser where it is shown to the user. The PHP code at that point is gone, stripped by the server when it was run.

Normal form behavior generally includes loading the page again (or a new page) - wherever the action points. This is the browser capturing the form data, sending it back to the server where the server can run more PHP with those inputs and then give back the browser a new HTML rendition with whatever changes might have resulted from that input.

Your current example blocks the form post (e.preventDefault()) so the form data never gets sent. Additionally, presumably the page initially loaded without any post data to start meaning the fruit text has no value. The only way it could have value is if the page was processed on the server (before being loaded) with the “letter” post data, but that will never happen here because, again, the form can never send it.

Your options are: allow for a page reload, or make a hidden, background request with JavaScript that runs PHP on the server and provides a response that JavaScript can read (Kirupa’s suggestion). This means you can’t use PHP post data in the page, though, because this page wouldn’t have access to the post data on the server, only the separate request being made with JS would. Anything you want in the page to reflect that data would have to be handled by JavaScript.

2 Likes

Other people have suggested that I use AJAX, which I am only vaguely familiar with. It seems like you are suggesting a similar thing, yes? Clearly I have to do more study because this all still seems convoluted to me.

Thanks for taking the time to lay that out.

AJAX is basically the same thing, though AJAX itself specifically relates to XML (thats the X in AJAX). Most people are passing around JSON payloads now. Both can be handled with XHR, despite XHR standing for XMLHttpRequest (yes, XML again). For JSON its just a matter of getting the raw text and throwing it into JSON.parse() (there’s actually support for JSON without manually parsing but its rarely used because it doesn’t work for IE). Of course you can send any text you want, even just a string of what fruit should be.

Here’s a quick googled tutorial that quickly shows the basics wrt PHP
https://www.developphp.com/video/JavaScript/Ajax-Post-to-PHP-File-XMLHttpRequest-Object-Return-Data-Tutorial

It can get a little convoluted so people generally stick to simple wrappers available in libraries like jQuery, where it then simply becomes something like

$.post( "example.php", { user_input: 'value' }, function(data) {
  // do something with returned data
})

Thanks. I’m going to check out the tutorial and then think on this. I think I have to re-work my architecture, which is more work than I want to do. But it seems like I"ll be sorry if I don’t set this up correctly.