Just recently picked up PHP for a project, currently I'm trying to get PHP to recognize when the submit button has been hit and to print "Success" using the code below (Ignore the fetchIntervals() that calls a javascript function):
<button class = "button" type = "submit" name = "submit" onclick = "fetchIntervals()" method = "POST">Submit</button>
<?php
echo("Test"); //Prints out successfully
if($_SERVER['REQUEST_METHOD'] == "POST"){
echo("Post"); //Does not print
if(isset($_GET["submit"])){
echo("Success");
}
}
if($_SERVER['REQUEST_METHOD'] == "GET"){
echo("Get"); //Prints successfully even though I'm using POST method
if(isset($_GET["submit"])){
echo("Success"); //doesn't print at all when button is pressed
}
}
?>
As said in the code I know it's entering into the PHP block since "Test" successfully prints out, but even though I'm using method = "POST" for my button the $_SERVER['REQUEST_METHOD'] == "GET" is returning true and it's not even registering the button being clicked.
CodePudding user response:
It is not clear from your code if the button
element is wrapped inside a form
element.
If it is not, the button should not be doing anything (i.e. it doesn't start a request to the server).
If it is, and the form has not got an attribute method="POST"
, it will send the form with the GET method (by default). If you want to set the method in the button
element, the attribute name is formmethod
and not method
(Button specs).
When you first load the page, you are sending a GET
request to the server. That is why the if($_SERVER['REQUEST_METHOD'] == "GET")
test is true and the echo("Get");
is executed.
A possible modification could be adding a form
tag as a parent of the button
element and set its attribute method="POST"
. Setting the method on the button itself is usually not necessary, unless you have more submit buttons.
As a side note, echo
is a language construct and not a function. Although it is allowed to call it with parenthesis, it is (wide) common practice to use it without.
Example: echo "Get";
.