Is it possible for a user to enter a value into a form and then, on submit, have the page redirect to a new one with the value entered into the form stored in a PHP variable?
This if my form code;
<form id="loc-search" method="post">
<input type="text" id="search-by-location" name="custom-location" value="" placeholder="Sheffield, UK"/>
<input type="submit" id="submit" value=""/>
</form>
Once the user has entered a value in #search-by-location
the page needs to redirect to weather.php
with the value stored in a PHP variable called $location
AJAX / JS aren't my strong suits so if someone could point me in the right direction that would be great
Add the argument action="weather.php"
to your form tag. Then, when clicked on the submit button, you will get redirected to that page. Depending on your method, in your case POST
, the input values will be available in the superglobal $_POST
array in PHP.
In your example, $location = $_POST["custom-location"];
will suffice. Note that the name, not the ID, determines the array key in the target PHP document.
Javascript or AJAX are not needed to achieve this.
This is just a normal form so why not just use $_POST
after the redirect on the weather.php
page:
$location = $_POST["custom-location"];
As @Tacticus pointed out you also need to have the form redirect (if you did not already do this in JS). By adding action="weather.php"
in the form:
<form id="loc-search" method="post" action="weather.php" >
...
</form>
As stated in other answers you should modify your form to look like this:
<form id="loc-search" method="post" action="weather.php">
<input type="text" id="search-by-location" name="custom-location" value="" placeholder="Sheffield, UK"/>
<input type="submit" id="submit" value=""/>
</form>
In your weather.php file, you can get the value from the $_POST global variable, just like this:
<?php
$location = $_POST["custom-location"];
//Interpret data
?>
Note that you can access the value of an input tag from your form witch was passed, with the input's name. In html you specify the following:
<input name="yourname" />
And when you want to access that value, you simply refer to his name.
$_POST['yourname']
If you use GET method for the form to pass the values, then you do the same, only the value will be stored in the $_GET global variable, so in your case with a GET method the variable initialization would look like this:
<?php
$location = $_GET["custom-location"];
//Interpret data
?>