I have a form which contains one text field. Now, I'm trying to echo out the contents of that input after the form was submitted. Here's my code for the same:
<script>
function postResultss()
{
document.write("<?php echo ($_POST['tweet1']); ?>");
}
</script>
<form method = "POST">
<input type = "text" name = "tweet1">
<br>
<input type = "submit" onclick = "postResultss()" />
</form>
The above code is inside a PHP file. However, nothing gets echoed out on submitting the form. The function does get called as expected, because I have tried echoing custom messages while debugging. However, nothing gets echoed out when I try to echo the value of $_POST['tweet1'], where tweet1 is the name of the input text field whose contents I'm trying to display.
What seems to be wrong here?
You do a submit and onclick. That goes wrong. Further, don't do a document.write!
Do this as better alternative (no php in js):
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') // check if post
echo htmlentities($_POST['tweet1']);
?>
<form method="post">
<input type="text" name="tweet1">
<br>
<input type="submit" value="Tweet!">
</form>
Rather than use javascript to write the content which, in your example wouldn't work, use php to generate the response for the user to see
<form method = "POST">
<input type = "text" name = "tweet1">
<br>
<input type = "submit" value='Submit' />
<div id='msgs'>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['tweet1'] ) ){
echo $_POST['tweet1'];
}
?>
</div>
</form>
The problem is that the javascript function is called before the form submits (so before php can print out the echo), and since the page updates the document.write is being overwritten from the new request.
Why dont you try something like this?
<form method = "POST">
<?php echo ($_POST['tweet1']); ?>
<input type = "text" name = "tweet1">
<br>
<input type = "submit"/>
</form>
or:
<script>
var text = "<?php echo ($_POST['tweet1']); ?>";
if(text != ""){
alert(text);
}
</script>
<form method = "POST">
<input type = "text" name = "tweet1">
<br>
<input type = "submit"/>
</form>
Related
I have a form that I use to send data to image.php from my home.php page.
<form class="d-flex" action="" method="post">
<input class="rounded-0 form-control" type="text" name = "name" placeholder="Explore. . ." aria-label="Search">
<button class="border searchfeature" id= "show" type="submit"><i class="fa fa-search"></i></button>
</form>
When I put action = "image.php" the page takes me to image.php page and displays what I want which is the image I type in the search form. However what I want is the action to remain action="home.php" on the same page but get the image back and display it in the home.php page after the form is submitted.
I hear Sessions are a good way to solve this but I have no idea how to display it back in the same page once the form is submitted. I know one way to solve this is to put the image.php code in the home.php page but I am keeping the codes separate to keep it cleaner.
Thanks!
Form View:-
make a id="createForm" in your <form>
and id = "name" in input field.
<form id="createForm" class="d-flex" action="" method="post">
<input class="rounded-0 form-control" type="text" name = "name" id = "name" placeholder="Explore. . ." aria-label="Search">
<button class="border searchfeature" id= "show" type="submit"><i class="fa fa-search"></i></button>
</form>
Jquery Ajax Code:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#createForm').on('submit', function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
type: "POST",
url: "data.php",
data: {name: name},
success: function(data){
$("#createForm")[0].reset();
$('#table1').html(data);
}
});
});
});
</script>
In your HTML
<div id="table1">
//Let jQuery AJAX Change This Text
</div>
data.php Page
<?php
//data.php
if(isset($_POST["name"]))
{
$name = $_POST["name"];
// select query with where clause name condition
echo $output;
}
?>
You can do this in several ways it all depends on what is going on on the 2nd file - are we staying there or just coming back with a response to the 1st one? because you can:
1st file:
<?php
if(isset($_GET['response'])){
echo 'The response: ' . $_GET['response'];
} else {
?>
<form id="createForm" class="d-flex" action="2nd.php" method="post">
<input class="rounded-0 form-control" type="text" name = "name" id = "name" placeholder="Explore. . ." aria-label="Search">
<button class="border searchfeature" id= "show" type="submit"><i class="fa fa-search">go</i></button>
</form>
<?php
}
2nd file:
<?php
$name = $_POST['name'] . " - Received!!!";
header("Location: 1st.php?response=$name");
The response will be in 1st.php:
The response: SomeNameValue - Received!!!
This is a very very simplified way - using header and $_GET method in the first file when the $_GET['response'] exists it shows the response and skips the form...
If you are planning on displaying something in the 2nd.php file than header is available for you but you can either create another form and send the response in a hidden input or use Javascript to window.location.assign("1st.php?response=") where $name variable is the $_POST['name'] after we processed it in 2nd.php.
But the first example is just form and PHP.
I have a code which its simplified version could look like this :
file1.php
$array = array();
$array = new randomObject(1);
$array = new randomObject(2);
require('file2.php');
file2.php
<form method="post" action="?">
<?php
foreach ($array as $a) {
<p><?php echo $a->getAValue();
<textarea rows="5" cols="70" name="textbox[]">
</textarea>
</p>
<?php } ?>
<input id="isTrue"> //true or false
<input type="submit" >
</form>
The user is supposed to write answers in the textarea and click on submit then his answers are compared to the randomObject values. Then it shows if it's true or false next to each textarea
You are looking for something that the fron-tend will handle for you and an AJAX call is exactly what you need.
First of all, name your form
<form id="myForm" method="post" action="?">
<?php
foreach ($array as $a) {
<p><?php echo $a->getAValue();
<textarea rows="5" cols="70" name="textbox[]">
</textarea>
</p>
<?php } ?>
<input id="isTrue"> //true or false
<input id="submitButton" type="submit" >
</form>
Now you have proper id's both on the submit button and on the form itself.
<script>
let submitB = document.querySelector("#submitButton");
submit.addEventListener("click", function(e) {
e.preventDefault();
});
</script>
From now on you just have to write a proper ajax call to the url you wanted to access and you will be set to go.
If you need help with that let me know and I will throw something your way.
I am guessing you want to retain the values entered by the user, since they go away if you submit the form. (Page reloads)
This can be done by altering the input fields. If a value was submited pass that value to each corresponding input field.
Something like that:
<textarea rows="5" cols="70" name="textbox[]" <?php if(isset(value[SOMETHING])){?> value="<?php echo value[SOMETHING]; ?>" <?php } ?> >
This is just an example of how it would work. Make sure you adapt it to your code!
I want to auto send values in a form in a hidden field.
This is my first form. When I submit this form 2 action occurred 1.) trigger js - onclick="displayResult()" and 2.) send form to update.php
<form action="update.php" method="post">
<select name=category[] id=category multiple="multiple" class=master>
<?php
$file = fopen("category.csv", "r");
while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
$category = $row[0];
?>
<option value="<?php echo $category;?>"><?php echo $category;?></option>
<?php
}
?>
</select>
<input type="submit" value="Save File" onclick="displayResult()" name="submit" >
</form>
This is my js and I tried to auto submit form with adding document.getElementById("myform").submit(); When I do var_dump I get NULL
<script>
function displayResult() {
var options = document.getElementById('master').options;
var values = [];
var i = 0, len = options.length;
while (i < len)
{
values.push(options[i++].value);
}
txt=(values.join(','));
alert(txt);
document.getElementById('masterlist').value = txt;
document.getElementById("myform").submit();
}
</script>
This is the form I need to auto send values via above js but not working. Please need help
<form action="update.php" method="post" name="myform" id="myform">
<input type="hidden" name="masterlist" id="masterlist" value="">
</form>
Firstly, you should add necessary ""
<select name=category[] id="category" multiple="multiple" class="master">
Than change submit to hidden and remove onClick
<input type="submit" value="Save File" name="submit" hidden>
Next, add another button which have an onClick event
<input type="button" value="Save" onclick="displayResult();">
At the end - fix your JS. You should refer to the id 'category', but you're refering to the class 'master', using getElementById()
var options = document.getElementById('category').options;
Working fiddle (little changed for fiddle purposes): jsfiddle.net
I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name
I have a search bar that uses a javascript function to submit the form when the user hits Enter (which is working) because it doesn't have a submit button, but I need to use php to handle the data in the textbox on post. The form is submitting, but on post it's not able to grab what was in the search textbox.
Here's the code:
<form id="siteWideSearch" name="siteSearch" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
</form>
Javascript:
if (event.keyCode == 13) {
document.getElementById("siteWideSearch").submit();
}
PHP:
if($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<script type=\"text/javascript\">window.alert(\"Post reached. Yay!!\");</script>";
echo "<script type=\"text/javascript\">window.alert(\"Search Criteria: ".trim($_POST['homeSearch'])."\");</script>";
}
I get the popup saying that post was reached, but the second popup just outputs "Search Criteria: " and nothing else.
You're missing the name attribute on your form input. Without it that value is not submitted.
<input id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
should be:
<input name="homeSearch" id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />