Reputation: 21
I have a text field and a submit button, when I click on the submit button I want to add on to my query string.
example
http://www.fakewebsite.com/?name=mike
But my name appears blank
Here is my code
<?php
if($_POST){
echo $_POST['name'];
}else{ ?>
<form action="http://www.fakewebsite.com/test.php?name=<?php $_SERVER['name']; ?>" method="post">
<label for="name">Name</label><input type="text" name="name" id="name" />
<input type="submit" name="submit" id="submit" />
</form>
<?php } ?>
Upvotes: 0
Views: 7441
Reputation: 2129
alternate solution
<?php
if(!empty($_POST)){
echo $_POST['name'];
}else{ ?>
<form action="http://www.fakewebsite.com/test.php" method="post">
<label for="name">Name</label><input type="text" value="<?=$_SERVER['name']; ?>" name="name" id="name" />
<input type="submit" name="submit" id="submit" />
</form>
<?php } ?>
Upvotes: 0
Reputation: 3345
POST
request differ from GET
requests in terms of how they send data to the server.
with get the data elements are appended to the url (like you tried).
with post the data elements are within the body of the http request.
This is problem 1: You are trying to pass the argument as a get parameter. this can work, but is not guarranteed to.
The other thing is, that you have an input field with the same name name
. So even if the first thing would work, the input field would override that data.
what can you do to fox that? you can add a hidden input field with a different name to send this input back to your server:
<form action="foo.php" method="post">
<input type="hidden" name="other_name" value="<?= $_SERVER['name'] ?>" />
<input type="text" name="name" value="" />
<input type="submit" />
</form>
And also keep the name collision in check.
Edit:
A third problem that just appeared to me <? $_SERVER['name'] ?>
does not output the data within $_SERVER['name']
.
To do That you should use
<?php echo $_SERVER['name'] ?>
// or, works sometimes
<?= $_SERVER['name'] ?>
Upvotes: 2