submitting form don't go as expected - php

I didn't even know how to search for this, but I tried anyways and found nothing. If it's already answered, I give my apologize.
I have this form:
<form>
<div style="width:140px;float:left">Nro Socio: <input type="text" id="legajo" name="legajo" size="10" /></div>
<div style="width:200px;float:left">Nombres: <input type="text" id="nombre" name="nombre" size="22" /></div>
<div style="width:200px;float:left">Apellido: <input type="text" id="apellido" name="apellido" size="22" /></div>
<div style="width:50px;float:left"><input type="submit" id="srch" name="srch" value="Buscar" onclick="offen()" /></div>
</form>
Where offen() goes:
function offen()
{
$sid = document.getElementById('legajo').value;
$nom = document.getElementById('nombre').value;
$ap = document.getElementById('apellido').value;
if ($sid == "" && $nom == "" && $ap == "") alert ("No se ha ingresado ningún parametro de búsqueda");
else var wnd=window.open('../php/srchSoc.php?sid='+$sid+'&nom='+$nom+'&ap='+$ap,'mywindow',
'width=680,height=350,location=0,menubar=0,toolbar=0,location=0');
}
Why I do this instead of using target="_blank" or "_new"? Because I need this to be popup like, and I found no way to make it happen with the form itself.
The page srchSoc.php does some query, and if the resulting rows is just 1, automatically sets opener location to the same page, but with a $_GET value. i.e: '..site/bSoc.php turns' to '..site/bSoc.php?s=1'
Instead, I'm getting that '..site/bSoc.php' turns to '..site/bSoc.php?legajo=&nombre=&apellido=' Just like the form fields names.
Function where I set opener location on srchSoc.php goes like this:
<script>window.opener.location='../files/bSoc.php?soc=".$row['c_socio']."';
window.close();</script>
Where $row['c_socio'] is a column of the query result.

You need to prevent the normal form submission. Change the form submit button to:
<input type="submit" id="srch" name="srch" value="Buscar" onclick="offen(); return false;" />
return false prevents the submit button from submitting the form.

Why not simply using
<form method="get" action="fileyouwanttogo.php">

Related

Submit button already clicked

I have a form that I want to submit and I check if any textbox has text so I can UPDATE something in a database.
This is the code for the form:
<form action="" method="POST"/>
CNP Nou: <input type="text" name="cnpN"/><br/>
Nume Nou: <input type="text" name="numeN"/><br/>
Prenume Nou: <input type="text" name="prenN"/><br/>
Data Nasterii Noua: <input type="text" name="dataNN"/> De forma AAAA-ZZ-LL <br/>
Sex Nou: <input type="text" name="sexN"/> F sau M <br/>
Numar Telefon Nou: <input type="text" name="telN"/><br/>
Adresa Noua: <input type="text" name="adrN"/><br/>
E-mail Nou: <input type="text" name="mailN"/><br/>
<input type="submit" value="Modifica" name="search2" class="submit" />
</form>
Then I check if the button is clicked so I can see if any textbox has text written in order to make an UPDATE in my database:
if (isset($_POST["search2"]))
{
if (!empty($_POST['cnpN']) || !empty($_POST['numeN']) || !empty($_POST['prenN']) || !empty($_POST['dataNN']) || !empty($_POST['sexN']) || !empty($_POST['telN']) || !empty($_POST['adrN']) || !empty($_POST['mailN']))
{
//php code for update
}
}
else
{
echo "<h4><b> Eroare! </b><h4>";
}
The problem is that without clicking the button I see the "Eroare!" message. If I remove that else statement and I click the button nothing happens to the database, even if I introduce something in the form.
I used the else statement just to see if that might be the problem or not.
I am looking through the code for some time and can't see the problem.
I know there are simpler ways to check the completed textboxes but I'm new to php and I thought it's easier this way.
The else clause belongs on the if not empty conditional.
When you first load the php script, there is no POST data present. That is expected since it is a GET request. This is why the initial conditional is false and the error message appears. POST will never be set on an HTTP GET request.
Submit button is not already clicked , but your code is outputting 'Eroare' because, initially, you don't have set any post data on page load, including search2. So you don't need else part of conditional unless you mark that an error occurred, but within the if(isset($_POST["search2"])){} block.
Otherwise, it will always output the 'Eroare'.
You first need to validate your form data, then to throw the error if any of form data doesn't fulfill the conditions.
About validation process, you would either need to implement some existing validation libraries or to extend your conditional to check for specific data, specific validation requirements.
Some of them would be required (not empty), some of them would require constrained/limited values from a list ( like gender field ), some would require number value validation ( phone ), an email field would require email value validation.
Also, you are missing the part for DB insertion.
Simplified code without advanced validation would be like this:
<?php
$post_search2 = filter_input(INPUT_POST,'search2'); //filter_input returns empty if input not set, and it is useful to filter and validate specific values;
if(!empty($post_search2))
{
$form_values = array('cnpN', 'numeN', 'prenN', 'dataNN', 'sexNN', 'telN', 'adrN', 'mailN'); //I have placed it in array to avoid having large code and simplify checks through iteration
$parsed_data = array();
foreach($form_values as $form_value){
$value = filter_input(INPUT_POST, $form_value);
if(!empty($value)){ //update parsed data only if form data is not empty
$parsed_data[$form_value] = $value;
}
}
//so if any of data is filled, do the updates
//this actually does same as !empty($_POST['cnpN']) || !empty($_POST['numeN']) || !empty($_POST['prenN']) && ...
// if you would require all data filled, check if count($parsed_data) === count($form_values) and that actually does same as this actually does same as !empty($_POST['cnpN']) && !empty($_POST['numeN']) && !empty($_POST['prenN']) && ...
//
if(count($parsed_data) > 0){
//php code for update
}else{
echo "<h4><b> Eroare! </b><h4>";
}
}
?>
<form action="" method="POST">
CNP Nou: <input type="text" name="cnpN"/><br/>
Nume Nou: <input type="text" name="numeN"/><br/>
Prenume Nou: <input type="text" name="prenN"/><br/>
Data Nasterii Noua: <input type="text" name="dataNN"/> De forma AAAA-ZZ-LL <br/>
Sex Nou: <input type="text" name="sexN"/> F sau M <br/>
Numar Telefon Nou: <input type="text" name="telN"/><br/>
Adresa Noua: <input type="text" name="adrN"/><br/>
E-mail Nou: <input type="text" name="mailN"/><br/>
<input type="submit" value="Modifica" name="search2" class="submit" />
</form>
Just remove the close tag from the form tag
ie, change <form action="" method="POST"/> to <form action="" method="POST">
If it doesn't solve your issue then use the following code snippet,
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
CNP Nou: <input type="text" name="cnpN"/><br/>
Nume Nou: <input type="text" name="numeN"/><br/>
Prenume Nou: <input type="text" name="prenN"/><br/>
Data Nasterii Noua: <input type="text" name="dataNN"/> De forma AAAA-ZZ-LL <br/>
Sex Nou: <input type="text" name="sexN"/> F sau M <br/>
Numar Telefon Nou: <input type="text" name="telN"/><br/>
Adresa Noua: <input type="text" name="adrN"/><br/>
E-mail Nou: <input type="text" name="mailN"/><br/>
<input type="submit" value="Modifica" name="search2" class="submit" />
</form>
PHP Code
if(isset($_POST["search2"]))
if(!empty($_POST['cnpN']) || !empty($_POST['numeN']) || !empty($_POST['prenN']) || !empty($_POST['dataNN']) || !empty($_POST['sexN']) || !empty($_POST['telN']) || !empty($_POST['adrN']) || !empty($_POST['mailN']))
{
//php code for update
}
Your code is working perfectly normal, output is showing because in the begining the "form" is not submitted and "if" it is not submitted then "else" should work and "else" is working. if you don't want it to be shown then you can remove else.it will work fine, also try not to end the form tag early
instead of
<form action="" method="POST"/>
use this
<form action="" method="POST"> `

Undefined Index when passing data to different HTML5 page

The following is one of my HTML pages.
<form id="regForm" method="post" action="enquiry_process.php" novalidate="novalidate">
<fieldset>
<legend>Personal Details</legend>
<label>First Name:</label>
<input type="text" name="owner" id="owner" /><br />
<label>Last Name:</label>
<input type="text" name="owner2" id="owner2" /><br />
</fieldset>
<p>
<input type="Submit" onclick="validateForm()"/>
<input type="Reset" value="Reset" />
</p>
</form>
The following is my 2nd HTML page.
<form id="bookForm" method="post" action="view_enquiry.php">
<?php
$fname = $_POST['owner'];
$lname = $_POST['owner2'];
?>
<input type="hidden" name="owner" value="<?php echo $fname; ?>">
<input type="hidden" name="owner2" value="<?php echo $lname; ?>">
<fieldset>
<legend>User Details</legend>
<p>Your First Name: <span id="confirm_fname"></span></p>
<p>Your Last Name: <span id="confirm_lname"></span></p>
<input type="submit" name="submit" value="Confirm Booking" />
<input type="button" value="Cancel" id="cancelButton" onclick="cancelBooking()" />
</fieldset>
The functions you see like validateForm() and cancelBooking() are Javascript functions that validate my form or return the user from the 2nd page to the 1st and I believe they have nothing to do with my question.
When I click submit on the first HTML page, it should pass on the value of the owner and owner2 to the 2nd page right?
I keep on getting Undefined index and after looking around, it seems like I have to use isset() or empty() in my PHP, but this seems to only mask my notices but does not actually fix it? When I just add isset(), it ends up giving my 3rd page Undefined Variable. The method on my forms are already post.
Is there another problem here? Thank you.
EDIT: The following is are my relevant Javascripts.
ValidateForm:
function validateForm(){
"use strict";
gErrorMsg = "";
var nameOK = chkOwnerName();
var nameOK2 = chkOwnerName2();
var isAllOK = (nameOK && nameOK2);
if(isAllOK){
isAllOK = storeBooking();
}
else{
alert(gErrorMsg);
gErrorMsg = "";
}
return isAllOK;
}
Storebooking:
function storeBooking() {
"use strict";
sessionStorage.firstname = document.getElementById("owner").value;
sessionStorage.lastname = document.getElementById("owner2").value;
window.location = "enquiry_process.php";
}
I have another function called getbooking that runs with the condition window.onload
function getBooking(){
//if sessionStorage for username is not empty
if((sessionStorage.firstname != undefined)){
//confirmation text
document.getElementById("confirm_fname").textContent = sessionStorage.firstname;
document.getElementById("confirm_lname").textContent = sessionStorage.lastname;
}
chkOwnerName and chkOwnerName2 are functions that validate the form with patterns and I don't think they're relevant.
I also updated my 2nd HTML page with Javascript related contents because I assumed it wasn't relevant at first.
You can debug with below code by adding it in your 2nd form page.
echo "<pre>"; print_r($_POST); die;
If your form data is not going to your 2nd form then Array() will come as empty.
u can try by print_r($_REQUEST[]); on second form top page (enquiry_process.php) , i hope the both the form is in same folder and name of second form page is "enquiry_process.php" .
Since u r sending data using post form u should be able to retrieve it by print_r($_POST); or print_r($_REQUEST);
"if(empty($var))" and "if(isset($var))" are conditions, they check something and execute code within "{}" if the test returns true. So they don't 'fix' problems.
Your script worked fine for me without your js. Maybe the problem.
Just try your code step by step. You will find what's wrong.

How to verify that email field is not blank before submitting form

Updated Question:
I added "required" to all fields, except the form will still submit if
first#second is used as the email. It submits even if missing the .com (or whatever).
How can I incorporate this validation too?
Thanks!
Original Question:
My site has a sign-up form with just an email field. Currently there are validators in place to verify the proper syntax of an entered e-mail, but the form will submit if the field is left blank. I need to verify that the field is not blank before submission. If it's blank, there should be some message that appears - similar to the ones that appear is no # symbol is included for instance.
My demo page is here.
The form html:
<div class='form animated flipInX'>
<h2>Sign Up</h2>
<form action="http://mydomain.us10.list-manage.com/subscribe/post" method="POST">
<input type="hidden" name="u" value="a324dfsf32erwdafdaf3dfsdsdf">
<input type="hidden" name="id" value="32df32rff2">
<input type="email" name="MERGE0" id="MERGE0" placeholder="Your Email Address" class="boxfield">
<button class='animated infinite pulse'>Let's Go!</button>
</form>
</div>
Any suggestions? Thank you
Use required in your input tags
The required attribute is a boolean attribute.
When present, it specifies that an input field must be filled out before submitting the form.
So your input should be
<input type="email" name="MERGE0" id="MERGE0" placeholder="Your Email Address" class="boxfield" required>
Look here for more information
Update :
type="email" is the common attribute of html5. If you need to validate you shall use the patten inside your input element
You shall use pattern="[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b
Here is the one use should use
<input type="email" required pattern="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b">
Here is the jsfiddle as per your updated question
You can add required attribute in input tags.
<input type="email" name="MERGE0" id="MERGE0" placeholder="Your Email Address" class="boxfield" required="true">
Luckily it's that easy
The best way to do this to add required attribute in input tags
Please check this solution in which i using jquery to check it is blank or filled
<div class='form animated flipInX'>
<h2>Sign Up</h2>
<form action="http://mydomain.us10.list-manage.com/subscribe/post" method="POST">
<input type="hidden" name="u" value="a324dfsf32erwdafdaf3dfsdsdf">
<input type="hidden" name="id" value="32df32rff2">
<input type="email" name="MERGE0" id="MERGE0" placeholder="Your Email Address" class="boxfield">
<button class='animated infinite pulse' type="submit" onClick="checkval();">Let's Go!</button>
</form>
</div>
<script>
function checkval()
{
var email_val=$("#MERGE0").val();
if(email_val.length>2)
{
}
else
{
alert("email is required.");/*there you change show the value which you want to show as a error message.*/
event.preventDefault();
/* this help to stop submit form*/
}
}
</script>
hopefully this may help you
I don't know if your question has been answer, but try this:
//The Input
<input type='email' id='email' placeholder='email' onchange='emailCheck()'>
//The Button
<button id='button' style='visibility:hidden'>Submit</button>
//Javascript
<script>
var input = document.getElementById('email').value;
if(input.indexOf("#") > -1){
if(input.indexOf(".com") >= input.length - 4){
document.getElementById('button').style.visibility = 'visible';
}else{
alert('Custom Invalid Email Alert');
}
}else{
alert('Custom Invalid Email Alert');
}
</script>
required is best option or u can use java script
like this
<script type="text/javascript">
function validateForm()
{
var a=document.forms["Form"]["answer_a"].value;
var b=document.forms["Form"]["answer_b"].value;
var c=document.forms["Form"]["answer_c"].value;
var d=document.forms["Form"]["answer_d"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
{
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>

Adding search query to the address bar

I have seen this done before but not sure how.
I am trying to have a search form go to pagename.php?q=[searchquery] so i can then get the searchquery from the address.
here is the form
<form class="sidebar-search">
<div class="input-box">
<input type="text" placeholder="Quick Product Search..." />
<input type="button" class="submit" value="" />
</div>
</form>
Here is the JS
// handle the search query submit on enter press
$('.sidebar-search input').keypress(function (e) {
if (e.which == 13) {
window.location.href = "search_results.php";
return false; //<---- Add this line
}
});
// handle the search submit
$('.sidebar-search .submit').click(function () {
if ($('.page-container').hasClass("sidebar-closed")) {
if ($('.sidebar-search').hasClass('open') == false) {
$('.sidebar-search').addClass("open");
} else {
window.location.href = "search_results.php";
}
} else {
window.location.href = "search_results.php";
}
});
Can anyone help with this?
You wouldn't actually need to do it using javascript
<form class="sidebar-search" method="get" action="search_results.php">
<div class="input-box">
<input type="text" placeholder="Quick Product Search..." />
<input type="submit" class="submit" value="" />
</div>
</form>
The action attibute defines the location (an URL) where the form's collected data should be sent.
The method attribute defines which HTTP method to send the data with (it can be "get" or "post").
This would probably help understand in detail.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/My_first_HTML_form?redirectlocale=en-US&redirectslug=HTML%2FForms%2FMy_first_HTML_form
But if you still need to use javascript here the answer
define an id for the search field as below
<input type="text" id="txtSearch" placeholder="Quick Product Search..." />
and then
var searchString = $('#txtSearch').val();
window.location.href = "search_results.php?q=" + searchString;
Do this:
window.location.href = "search_results.php?q=" + $(".sidebar-search input[type=text]").val();
Or you can give an id to the search and get the value of the element with that ID.
if you hit enter/submit you go to search.php?query=value
<form method="get" action="search.php" >
<input name="query" type="text" />
<input type="submit" value="search" />
</form>

Only send form (get) data if field is fulfilled (not validation)

I have a form, that is this one
<form method="get" action="<?php bloginfo('url'); ?>">
<input name="date-beginning" type="text" class="datepicker" />
<input name="date-end" type="text" class="datepicker" />
<input name="s" type="text" />
<input type="submit" value="Ok" class="botao-pequeno botao-pequeno-input" />
</form>
Well, when the user sends all the fields, we get this response:
http://myblogurl.com/?s=example&date-beginning=05/05/05&date-end=07/07/07
If he doesn't fill, for example the date-beginning field we get http://myblogurl.com/?s=example&date-beginning=&date-end=07/07/07
What I want is that if he doesn't fill the field, for example date-beginning, the form still be sent, but variable don't to get sent, like this: http://myblogurl.com/?s=example&date-end=07/07/07
Is there a way to do it? How?
var form = document.forms[0];
form.addEventListener('submit', function(){
var a = document.getElementsByName('date-beginning')[0];
if(a.value === '')
a.disabled = true;
});
karaxuna's anwser works. I just adapted it to jQuery, if any one is interested, this is the code
$("#the-form").submit(function() {
if($('#the-field').val() === ''){
$('#the-field').attr('disabled',true);
}
if($('#the-other-field').val() === ''){
$('#the-other-field').attr('disabled',true);
}
});

Categories