Multiple fileds : remember input values after submit - php

I have a multiple field input and I want to remember the input values after submitting it , how can I do that using php or maybe another language if it is possible?
I have this input:
<input type="text" name="passport[]" class="form-control" aria-describedby="basic-addon1"required/>
I have tried something like this :
value="<?php if(isset($_POST['passport'])) { echo $_POST['passport'][$i]; } ?>"
but nothing works.

You can use browser local storage to keep the value after form submission.
<form method="post" action="" onSubmit="return saveElement();">
<input type="text" name="passport[]" id="password"/>
<input type="submit" name="submit" value="save"/>
</form>
<script type="text/javascript">
document.getElementById("password").value = localStorage.getItem("password");
function saveElement() {
var passValue = document.getElementById("password").value;
if (passValue == "") {
alert("Please enter a password first!");
return false;
}
localStorage.setItem("password", passValue);
location.reload();
return false;
}
</script>

Related

how to show error in jquery after clicking submit button

My problem is that after clicking on submit button the page will go to php file any way my html code is like this
<form action="register.php" method="post">
<input type="text" name="name" id="name"><div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
and my jquery code goes like this
$('#name').focusout(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter name")
}
});
$('#button').click(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter your name")
}
});
but after clicking submit button it redirects to php file and doesn't show any error and store blank data in the database.
Because your input type is submit you can either change the type to button or add event.preventDefault() to avoid automatic passing of form
use event.preventDefault()
$('#button').click(function(e) {
e.preventDefault();//this will stop form auto submit thus showing your error
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
}
});
Or
<input type="submit" value="submit" id="button">
change to
<input type="button" value="submit" id="button">//also prevent form auto submit thus will show the error
Well you need to stop the code to execute after error has been detected. For example you can simple use return false or return:
$('#name').focusout(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter name")
}
});
$('#button').click(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
return false;//add this
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="register.php" method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
I strongly recommend never to assign validation to a submit button click.
Instead assign the submit event handler of the form.
I also added trim and removed the content of the error from the code.
$(function() {
$('#name').focusout(function() {
var empty = $.trim($('#name').val()).length == 0;
$('#adiv').toggle(empty);
});
$('#form1').on("submit",function(e) {
$('#name').focusout();
if ($('#adiv').is(":visible")) {
e.preventDefault()
}
});
});
#adiv { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="register.php" method="post" id="form1">
<input type="text" name="name" id="name">
<div id="adiv">please enter name</div><br/>
<input type="submit" value="submit" id="button">
</form>
Please check this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="button" value="submit" id="button">
</form>
<script>
$(document).ready(function(){
$('#button').on('click',function(){
if($('#name').val() == ''){
$('#adiv').text("Please enter name!!");
}else{
$('#adiv').text($('#name').val());
}
})
})
</script>
try this..:D
function validateFunction(){
if(document.getElementByID('name').value.length==0){
document.getElementByID('adiv').innerHTML = "please enter your name";
return false;
}
return true;
}
<input type="submit" value="submit" id="button" onclick="return validateFunction();" />
$('your-form').on('submit', function(e) {
e.preventDefault();
//your code bere
});
preventDefault stop the normal submit behaviour of your browser so that you can trigger any event you want

Only pass GET information if isset

I am using a form with the method of GET to add to the query string.
I am running into an issue. When the form is submitted every field is sent and added to the query including with no values.
Example:
http://web.com/?filter-types=news&filter-document-type=&filter-topics=we-have-a-topic&filter-featured=&filter-rating=
Can I not add these to the query string if they are not set? !isset() or is there another way to do this?
You could alternatively manipulate the form inputs thru javascript, just a Mike said in the comments, on submit check the fields, if empty, disable them so that they wont be included on submission.
This is just the basic idea (with jQuery):
<form method="GET" id="form_inputs">
<input type="text" name="field1" value="field_with_value" /><br/>
<input type="text" name="field2" value="" /><br/><!-- empty field -->
<input type="text" name="field3" value="field_with_value" /><br/>
<input type="submit" name="submit_form" id="submit_form" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('input[name="submit_form"]').on('click', function(e){
e.preventDefault();
$('form').children().each(function(i, e){
if($(e).is('input') && $(this).val() == '') {
$(this).prop('disabled', true);
// or $(this).attr('name', '');
}
});
$('form').submit();
});
</script>
Or if you do not want to use jquery at all:
document.getElementById('submit_form').addEventListener('click', function(e){
e.preventDefault();
var children = document.getElementById('form_inputs').childNodes;
for(i = 0; i < children.length; i++) {
if(children[i].type == 'text' && children[i].value == '') {
children[i].disabled = true;
}
}
document.getElementById('form_inputs').submit();
});
The reason all those keys show up in query string is because they exist as inputs in the form. If you don't want them sent, remove them from the form, or at least give them some meaningful defaults.
I guess you are looking a condition
if (!empty($_POST['var'])) {
}
OR
if (!isset($_POST['var']) && !empty($_POST['var'])) {
}

Redirect GET form with action in another url

I have a form with the action set to "/resutls". But i have a txt input and i want to check if that is not empty to redirect to another location than "/results". Is this possible?
Code example as below:
<form id="results" action="/results" method="get">
<select id="country" name="country">
....
</select>
<input type="text" name="id">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Any ideas? Can this be done with jquery?
Sure you can do that in the submit handler. Warning: I wouldn't give a form control a name of id. It does cause confusion: if this refers to the form, should this.id refer to the id of the form or the text field with name="id"?
if( !!this.somefield.value ) { //did not want to write this.id.value !!!!
this.action = '/other-url';
} else {
this.action = '/results';
}
$(function() {
$('#results').on('submit', function(e) {
e.preventDefault(); // just so we can see that form action changes
if( !!this.somefield.value ) {
this.action = '/other-url';
} else {
this.action = '/results';
}
alert( this.action );
//$(this)[0].submit(); //now submit the form
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="results" action="/results" method="get">
<select id="country" name="country">
</select>
<input type="text" name="somefield">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Yes it is possible. Just set the form element's action property using jQuery .prop().
As a simple example:
var valid = false;
// go though validation here
if (false === valid) {
$('#results').prop('action', '/some/url/to/redirect/to');
}
HTML5 provides the "required" attribute wich will prevent the form for being posted, use it like this
<input type="text" name="id" required="required">
or, if you prefer to redirect to other page instead, you can do this
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$("#results").submit(function (e){
e.preventDefault();
if($("#results input[name='id']").length < 1){
window.location.href = "your detiny url";
}
else{
this.submit();
}
});
</script>

loading same page in php on basis of query

I am trying to do nothing if search field is left blank, and load another page if something entered.
so, How to load same php page when input textbox value is blank, and a different php page when input text value is not blank...?
for e.g.
<input id="srch" type="text" name="query" >
if value of this textbox is "", then same php page should get loaded
else, other page....
is there any way in php or javascript..?
You could use a simple onsubmit function for your form:
<form method="post" action="<?php $_SERVER['PHP_SELF']?>" onSubmit="return validate()" id="searchForm">
<input id="srch" type="text" name="query" >
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function validate(){
if(document.getElementById('srch').value != ''){
document.getElementById('searchForm').action = 'YOUR_OTHER_PAGE';
}
}
</script>
In the above example, then the form is submitted, it goes to a validate() function in javascript. This function quickly checks to see if the #srch is empty. If it's not then it changes the action of the form to the page that you designate. I set that value to YOUR_OTHER_PAGE, and you would have to change it to the appropriate page. If the value of #srch is empty then it keeps the action which I set as PHP_SELF.
In PHP, in the script that checks the contents of the query, you can do this:
if( isset($_GET['query']) && $_GET['query'] != '' ) {
header('Location: someotherpage.php?query=' . urlencode($_GET['query']));
exit();
}
This qill instruct the browser to go to someotherpage.php
In PHP - after submiting the form - let's say to a script called decide.php
it's content:
if (!isset($_GET['query']) || $_GET['query']=='' )
include "emptysearchlanding.php";
else
include "somethingelse.php";
Here is the code that I use you can decide what to do by using inputString.length == 0 for blank input and just do if statement to execute your second function.
the code that I included in my answer is used to post the input automatically to the php file.
javascript :
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0)
{
$('#suggestions').hide();
}
else
{
$.post("http://www.example.com/suggest.php", {queryString: ""+inputString+""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
}
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
function outoffocus() {
setTimeout("$('#suggestions').hide();", 200);
}
</script>
HTML :
<form id="search" action="/search.php" method="get">
<input type="text" name="search" id="inputString" onkeyup="lookup(this.value);" onblur="outoffocus()" onfocus="lookup(this.value);"/>
<input type="submit" value=" " />
<div class="suggestionsBox" id="suggestions" >
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</form>

Verify a submitted form without the PHP redirection to the action page

I'd like to submit a form thanks to AJAX and display the error messages contained in "form_treatment.php" (form verification) without the php redirection to "form_treatment.php" when I submit. What have I to write in the following lign ?
$.post("form_treatment.php",name, ???);
I have a basic form in form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
This form is treat in form_treatment.php :
if ( empty($_POST['user_name']) ){
echo 'You have to enter your name.';
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
echo 'Name already used.';
} else {
// Entering the name in the DB
}
}
You can try something like the following:
<form id="myForm" method="post" action="form_treatment.php" >
<span id="message"></span>
<input type="text" name="user_name" value="Your name..." />
<input type="submit" >OK</button>
</form>
And the javascript:
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
}
});
return false;
});
You can accomplish this by two ways
1st One in the same page
2nd one via AJAX
The first way can be done like this
<?php
if(isset($_POST['sub']) && $_POST['sub'] == 'true'):
if ( empty($_POST['user_name']) ){
echo 'You have to enter your name.';
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
echo 'Name already used.';
} else {
// Entering the name in the DB
}
}
endif;
?>
<form method="post" action="<?php echo $PHP_SELF; ?>" >
<input type="text" name="user_name" value="Your name..." />
<input type="hidden" name="sub" value = "true" >
<button type="submit" >OK</button>
</form>
The 2nd way via ajax
can be done like this
<div id="errors"></div>
<form method="post" id="myFrm">
<input type="text" name="user_name" value="Your name..." id="name" />
<button type="submit" >OK</button>
</form>
<sctipt>
$("#myFrm").submit(function() {
var NameFromForm = $('#name').val();
$.post("form_treatment.php", { "user_name": NameFromForm },
function(data){
$("#errors").html(data);
});
event.preventDefault();
});
</script>
If you need any explanation leave a comment

Categories