PHP keep form info after submit form failed - php

Hello
I am building a form in a mvc system view, and i want that all the inserted values will be kept,in case of form submit failure.
How can this be done: i tried like (example for a field):
<label for="user_firstname">Nume</label>
<input id="user_firstname" type="text" name="user_firstname" value=<?= $_POST['user_firstmane'] ?> >
<? if (isset($errors['user_firstname'])): ?>
<span class="error"><?= $errors['user_firstname']; ?></span>
<? endif; ?>
but of course, it doesn't work the first time (when no post action is done).
what is the simplest way to do this? any ideas?
thank you

Just loop through the DOM in javascript and put the PHP $_POST data into the input.value
<script type='text/javascript'>
<?php
echo "var jsArray = new Array();";
foreach ($_POST as $key=>$value){
echo "jsArray['$key'] = '$value';"; //turn it into a javascript array
}
?>
// Grab all elements that have tagname input
var inputArr = document.getElementsByTagName("input");
// Loop through those elements and fill in data
for (var i = 0; i < inputArr.length; i++){
inputArr[i].value = jsArray[inputArr[i].name];
}
</script>

I would suggest something like:
<label for="user_firstname">Nume</label>
<input id="user_firstname" type="text" name="user_firstname" value=<?(isset($_POST['user_firstname']) ? $_POST['user_firstname'] : ""; ?>>
<? if (isset($errors['user_firstname'])): ?>
<span class="error"><?= $errors['user_firstname']; ?></span>
<? endif; ?>
You also had a typo in the $_POST["user_firstmane"] should be $_POST["user_firstname"] :)

value="<?php echo isset($_POST['user_firstname'])? $_POST['user_firstname'] : "" ?>"

You mean you want to keep the value of the form when it failed to submit? You can use $_SESSION to store the value in the check page. For example:
check.php
<?php
session_start();
if (strlen($_POST['user_firstname']) < 5) { //for example
$_SESSION['user_firstname'] = $_POST['user_firstname'];
}
?>
In your current form. change value=<?= $_POST['user_firstmane'] ?> to value="<?=$_SESSION['user_firstname']?>", so:
<label for="user_firstname">Nume</label>
<input id="user_firstname" type="text" name="user_firstname" value="<?=$_SESSION['user_firstname']?>" />
<? if (isset($errors['user_firstname'])): ?>
<span class="error"><?= $errors['user_firstname']; ?></span>
<? endif; ?>

<input id="FirstName" name="FirstName" placeholder="First name" title="First Name" required="" tabindex="1" type="text" value="<?php if(isset($_POST['FirstName'])){ echo htmlentities($_POST['FirstName']);}?>"/>
This code is much more easier to keep form info after submit form failed.

Related

php move data from one form to another but with multiple input ids

I have a form where I set textarea field id by for loop using php
<?php
foreach ($restaurant as $rest_data) {
?>
<textarea class="form-control" name="<?= 'comment_' . $rest_data->id ?>" id="<?= 'comment_' . $rest_data->id ?>" rows="3" placeholder="Leave a note for Restaurant (optional)" ></textarea>
<?php
}
?>
but I need this field value in another form's hidden field with their respective ids using jQuery or any other method like php session or anything
I am assuming that you want to create duplicate hidden elements for textarea fields of one form to another form . I would suggest you to bind events on keypress of the textarea and populate the value of textarea into hidden fields.
1. Modify your code of generating textarea
<?php
foreach ($restaurant as $rest_data) {
?>
<textarea class="form-control" name="<?= 'comment_' . $rest_data->id ?>" id="<?= 'comment_' . $rest_data->id ?>" rows="3" placeholder="Leave a note for Restaurant (optional)" onkeypress="fillInDuplicate(this)" ></textarea>
<?php
}
?>
Create hidden fields in Another form
<?php
foreach ($restaurant as $rest_data) {
?>
<inpupt type="hidden" name="<?= 'comment_' . $rest_data->id.'-hidden' ?>" id="<?= 'comment_' . $rest_data->id.'_hidden' ?>" />
<?php
}
?>
Write a simple javascript , which will duplicate the data from textarea to hidden input field .
function fillInDuplicate(element){
document.getElementById(element.id+'_hidden').value = element.value;
}
I hope this helped.
save textarea value in Session and then save this in hidden field and on submission get this value where u submit your form or get this value anywhere...
<input type="hidden" id="comment_id" name="comment_id" value="<?=$SESSION['comment_id']?>">
You can do something like this you can set textarea with id and value using this
<?php for($i = 0;$i <= 10;$i++){ ?>
<input type="hidden" name="counterarray[]" value="<?php echo $i; ?>" />
<textarea name="data<?php echo $i; ?>" id="myid<?php echo $i; ?>"></textarea> <?php } ?>
Then,
While in the hidden part you can use counterarray to loop to same textarea ..Correct me if you need anything else.
Create a hidden field for each textarea
$('textarea[name^="comment"]').each(function(i,v){
$('#main-form').append('<input type="hidden" id="comment_id" name="comment_id" value="'+$(v).attr('id')+'">');
});
Trigger this code when you click the button to open the #main-form

How to save session data in to text box value?

I have some data in a session and I want to save it in text box value, using PHP. But the problem is when saving, just first token of string will be saved, like below example:
<?php session_start();?>
<html >
<head>
</head>
<body>
<form >
<?php echo $_SESSION['institute']="rebaz salih" ?>
<input type="text" <?php echo "value=".$_SESSION['institute']; ?> required />
</form>
</body>
Output will be:
rebaz salih
rebaz
Couple of things:
<?php echo $_SESSION['institute']="rebaz salih" ?>
Is this supposed to be the assignment? or just a print line? in any case, try getting rid of the echo.
Both #edCoder, and #chethan194 are on the right track... the value belongs on the outside, but you really should be using a new variable for institute. For example:
//htmlspecialchars will clear out any quotes, etc so it will work in the browser.
<?php
$value = htmlspecialchars($_SESSION['institute'], ENT_QUOTES);
?>
<form >
<input type="text" value = "<?php print $value; ?>" required />
</form>
Here is the full example:
<?php
php session_start();
//i don't know where you get the institute, so i will leave it here for now...
$_SESSION['institute']="rebaz salih";
$value = '';
if (!empty($_SESSION['institute']))
{
$value = htmlspecialchars($_SESSION['institute'], ENT_QUOTES);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" value = "<?php print $value; ?>" required />
</form>
</body>
You can put the value attribute outside php
<?php echo $_SESSION['institute']="rebaz salih" ?>
Wrong - <input type="text" <?php echo "value=".$_SESSION['institute']; ?> />
Right - <input type="text" value = "<?php echo $_SESSION['institute'];?>" />
</form>
<input type="text" value="<?php echo $_SESSION['institute']; ?>" required/>

Update Textbox on after PHP GET

I'm a complete beginner with web development and I'm facing a problem. I have a navigation bar, with a search form that 'gets' to search.php
Sample URL : http:/....search.php?s=asdas
I would want to get the value of $_GET['s'] and place it in a textbox with the id = 'filter-searchbox'
My code so far goes like this :
<?php
if(isset($_GET['s'])){
$searchWord = $_GET['s'];
?>
<script>
document.getElementById('filter-searchbar').value =<?php $searchWord ?> ;
</script>
<?php }
?>
<h3> <div class="label label-default"> Search for Events </div></h3>
<BR>
<div id="filter" class="col-md-3">
<input id='filter-searchbar' name='searchWord' type="text" class="form-control" placeholder="Search Events..." value= "" ><br>
Thank you very much!
Rewritten the code, Try this,
<?php
$searchWord="";
if(isset($_GET['s'])){
$searchWord = $_GET['s'];
}
?>
<input id='filter-searchbar' name='searchWord' type="text" class="form-control" placeholder="Search Events..."
value= "<?php echo $searchWord;?>" ><br>
You missed echo and should write this echo "'".$searchWord ."'"; below the input tag.
Because the document.getElementById('filter-searchbar')... statement would executed successfully after only the dom is ready.
<h3> <div class="label label-default"> Search for Events </div></h3>
<BR>
<div id="filter" class="col-md-3">
<input id='filter-searchbar' name='searchWord' type="text" class="form-control" />
<?php
if(isset($_GET['s'])){
$searchWord = $_GET['s'];
?>
<script>
document.getElementById('filter-searchbar').value = <?php echo "'".$searchWord ."'"; ?> ;
</script>
<?php }
?>
document.getElementById('filter-searchbar').value = is missing an echo statement.

How to change input value dynamically

I want to change an input value depending on a $_POST variable. Something like this:
<?php if ($_POST['yourname'] != "")
{
$('input[name=yourname]').attr('title', $_POST['yourname']);
} ?>
But it doesn't work. How can I do that?
Thanks!
EDIT: I have this input:
<input class="clearme" name="yourname" type="text" title="Insert your name" />
Add directly to html:
<input class="clearme" name="yourname" type="text" title="Insert your name" value="<?php echo isset($_POST['yourname']) ? $_POST['yourname'] : ''; ?>" />
You can't use javascript in PHP. PHP runs on the server, while javascript runs in the clients browser.
You need to do this in pure javascript, not PHP.
Try this in the one file, replacing 'name_of_cur_file.php' with the name of the current php file.:
<?php
if($_POST['yourname'] > ""){
$yourname = $_POST['yourname'];
}else{
$yourname = ""; // set to avoid errors
}
?>
<form action="name_of_cur_file.php" method="post">
<input type="text" value="<?php echo $yourname;?>" />
<input type="submit" value="go" />
</form>
WARNING!!! - Lacking any validation for this example!!!
If you want the code sent from the server to execute then:
<?php if ($_POST['yourname'] != "")
{
<script type="text/javascript">
$(document).ready(function () {
$('input[name=yourname]').attr('title', $_POST['yourname']);
});
</script>
} ?>
You have jquery code in php.You have complete first php tag then you have write your jquery code in script code like
<?php if ($_POST['yourname'] != "")
{
?>
<script>
$('input[name=yourname]').attr('title', $_POST['yourname']);
</script>
<?php
} ?>
You can also write php code only like
<?php
$title="Insert your name";
if ($_POST['yourname'] != "")
{
$title=$_POST['yourname'];
} ?>
<input class="clearme" name="yourname" type="text" title="<?php echo $title; ?>" />

Add value on textbox upon clicking submit

Is it possible to create multiple html text inputs on my
<form method="POST" id="2">
using:
<input type="text" value="">
with an initial value of none and fill it with a value after clicking submit from a previous
<form method="POST" id="1">
Can anyone help me with this?
Thanks in advance! By the way, I'm using PHP.
This question is a bit vague and tagged incorrectly.
PHP is executed server side. The only way to modify your form is by using Javascript.
The answer to your "Is it possible" question is simply yes.
<form name="myform" action="handle-data.php">
Input: <input type='text' name='name' value='none' />
Submit
</form>
<script type="text/javascript">
function submitform()
{
// Do things here
document.myform.submit();
}
</script>
#zerey: I coded up this commented contrived example of what I think you might have been hoping to achieve using PHP only and I've combined it all into one form --
<?php
if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST")
{
$foo = intval($_POST['foo']);
$bar = $_POST['bar'];
if (count($bar) > 0)
{
// the additional inputs that were created now contains data
// and furter validation can take place here
}
}
if (!isset($foo))
{
$foo = 0; // default the # of inputs field to 0
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
<div>
<label for="foo"># inputs:</label>
<input type="text" name="foo" size="3" maxlength="1" value="<?php echo $foo; ?>">
<input type="submit" value="Submit">
</div>
<?php
// a check to limit the amount of additional inputs that can be
// created
if ($foo < 10 && $foo > 0)
{
?>
<div>
<?php
// loop to output the # of inputs the user previously entered
for ($i = 0; $i < $foo; $i++)
{
?>
<br>
<label for="bar[<?php echo $i; ?>]"><?php echo $i + 1; ?></label>
<input type="text" name="bar[<?php echo $i; ?>]" id="bar[<?php echo $i; ?>]" value="<?php echo $bar[$i]; ?>">
<?php
}
?>
</div>
<?php
}
?>
</form>
Do they have to be separate forms?
You could use something like the jQuery Form Wizard Plugin to split up the form in the UI and use the step_shown event to populate the fields you need.

Categories