I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.
Related
I have some javascript and php code written to validate a field. Both codes are to validate whether the field is not empty, is within a limit of 35 characters and contains only alphabetic characters and a hyphen(-). What i want to do is for both the javascript and php to validate simultaneously and show they're messages for entering incorrect data but it only seems that the javascript is validating properly due to the fact that an alert pops up but no message is shown from the php side. Here is my code :
<script type="text/javascript">
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
var ck_password = /^[A-Za-z-]/;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if(!ck_password.test(stringf))
{
alert("Family name can only contain alphabetic characters and hypehns(-)");
return false;
}
return true;
}
</script>
<?php
if (isset($_POST['submit'])) {
$flagf = false;
$badcharf = "";
$stringf = $_POST["family"];
$stringf = trim($stringf);
$lengthf = strlen($stringf);
$strmsgf = "";
if ($lengthf == 0) {
$strmsgf = '<span class="error"> Please enter family name</span>';
$flagf = true;}
else if ($lengthf > 35) {
$strmsgf = '<span class="error"> Can not enter more than 35 characters</span>';
$flagf = true;}
else {
for ($if=0; $if<$lengthf;$if++){
$cf = strtolower(substr($stringf, $if, 1));
if (strpos("abcdefghijklmnopqrstuvwxyz-", $cf) === false){
$badcharf .=$cf;
$flagf = true;
}
}
if ($flagf) {
$strmsgf = '<span class="error"> The field contained the following invalid characters: '.$badcharf.'</span>';}
}
if (!$flagf) {
$strmsgf = '<span class="error"> Correct!</span>';}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes() && validateTextBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Could anyone help me with this?
Your JavaScript and PHP cannot execute simultaneously because the former happens in the user's browser before the form is POSTed and the latter happens after this once the form has reached the server.
You can verify this by inspecting the source code of your webpage in the browser: there's no PHP!
If your JavaScript makes the catch, nothing is sent to the server because you return false. In practice it makes sense to have the server-side checks in place in case:
Someone is tricky and modifies the form after it's validated but before it's sent.
JavaScript is disabled or breaks for some reason.
The way this form works is that you have a JS function in the form's onsubmit property which can prevent the form's submission if a value is wrong. If your JS function returns false because of an error, the form will never be submitted.
In order to get the functionality you want, you need to perform the checks on the server side only, but you'll need to submit the form each time for that to occur...
An alternative way would be to check the entered values when the user finishes adding a value to each of your text fields, i.e. attach a JS function to the fields' blur() property, and make an AJAX call to your server that will validate the field contents before the form is actually submitted.
You can use jQuery's validate plugin for more complex validations, if these can be done on the client side, as well:
http://jqueryvalidation.org/
As paislee stated there is no way you can simultaneously run php and javascript. There are however dynamic requests you can send to run some php code and it's called AJAX. This will also not ensure an absolutely accurate simultaneous execution but will be closer to what you aim for.
I have a multi-step order form built in this manner:
Step 1: Choose category via radio button
The "Next" button is just an image that has an onclick function hides the current div with the radio buttons, and displays a new div with the next step in the process.
Step 2: Textarea, checkbox -> Dynamic price
Contains a textarea, a dynamic price, and four checkboxes. The price changes depending on the number of characters in the textarea and the choices in the checkboxes. JQuery script is used in order to do that. Again, the "Next" button is just an image that upon activating the onclick function hides the current div, and displays the div containing the next step in the form.
Step 3: Personal Data
And here is my problem. Here where the user inserts name, email and so on. The "Next" button is again just an image that upon activating the onclick function hides the current div and displays the div containing the next step. How do i make the form fields in this step required in order to allow the user to advance to the next step. The code i have for hiding and showing the divs is as follows:
<script type="text/javascript">
function toggleDiv(id, flagit) {
if (flagit == "1") {
if (document.layers) document.layers[''+id+''].visibility = "show"
else if (document.all) document.all[''+id+''].style.visibility = "visible"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
}
else`if (flagit == "0") {
if (document.layers) document.layers[''+id+''].visibility = "hide"
else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"`
}
}
//-->
</script>
That is a horrible (and wrong) piece of old code.
here is an update that actually still handles Netscape4 (the layers part)
You need to show me the rest of the script where you toggle. You need to add validation to
THAT part, not the toggle.
For example, using
<form onsubmit="return validate(this)">
and
<input type="image" src="next.png" />
you can do this (plain JavaScript, the show and hide in jQuery is shown elsewhere on the page):
var currentStep=1;
function toggleDiv(id,flagit) {
if (document.getElementById) document.getElementById(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.all) document.all(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.layers) document.layers[id].visibility = (flagit)?"show":"hide";
}
function validate(theForm) {
if (currentStep == 1) {
if (theForm.category.value....) {
alert("Error in category");
return false;
}
currentStep++;
toggleDiv("part1",0);
toggleDiv("part2",1);
return false; // do not submit
}
if (currentStep == 2) {
if (theForm.price.value....) {
alert("Error in price");
return false
}
currentStep++;
toggleDiv("part2",0);
toggleDiv("part3",1);
return false; // do not submit
}
if (currentStep == 3) {
if (theForm.name.value....) {
alert("Error in name");
return false
}
return true; // submit
}
}
Well, since you have tagged your question with jQuery, why not actualy use it and let jquery handle all platform specific issues.
function toggleDiv(id,flagit) {
if( flagit ) {
$("#"+id).show();
} else {
$("#"+id).hide();
}
}
Let me know if this works.
I have a multi page form (pages separated with hidden divs)
All of it is wrapped in form tags, with a submit button. However when the user clicks the submit button at the end, it will check certain criteria on the form. If all good, it will allow the form to submit, else it will preventDefault().
However in IE8+ (maybe lower too), it simply never submits the form. I have console.log'd the JS, and it fires where it should, just IE doesn't submit the form.
I then added a $('#form').submit() call to manually submit it, which it did, but no data got sent...
Any ideas? Sorry if this is a bit vague.
Html
<form method="POST" action="/members/transfer_manager.php" name="f1" id="TM_MainForm">
** Loads of form fields & table structure **
<input type="submit" class="TM_Button" id="TM_submitTransfer" name="save" value="Transfer my account{if $isclientaresellerVAL}s{/if} »" />
</form>
JavaScript
$('#TM_submitTransfer').click(function(e)
{
console.log($.TM_submitTransferERR);
// Submit the form? Let's check first matey.
$.TM_submitTransferERR = false;
if(($('#TM_Movedate').val() == '') && (!$('#TM_MoveNow').is(':checked')))
{
$('#TM_MoveDate_ERR').html($.ObjectER + "Please choose");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check we have some…
// Set the # of xfers
var rsxfers = $("#TM_UsernamesSubACCTSTAGC").tagit("assignedTags");
var fsxferssplitLGNTH = rsxfers.length;
var OnlySubAccts = $('#TM_only_sub_accounts').prop("checked");
console.log($.TM_submitTransferERR);
if((OnlySubAccts == true) && (fsxferssplitLGNTH < 1))
{
alert("You have not chosen any accounts to transfer");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check TOS
if(!$('#TM_Tos').is(':checked'))
{
// Show error?
$('#TM_Tos').focus();
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Error, return false.
if($.TM_submitTransferERR === true)
{
console.log("Don't do it!");
console.log($.TM_submitTransferERR);
e.preventDefault();
return false;
}
console.log($.TM_submitTransferERR);
console.log("do it!");
$('#TM_MainForm').submit();
return true;
});
please i need your help with an issue.
I have two forms on my homepage that i'll like users to fill and submit at different times. My problem is that i'll like to have only one processing page for both of them. Normally i can do this in seperate pages. But i'll like to know if doing it on the same page is possible.
Okay.. If i submit form A, on the action page, wont there be Undefined Index for variable of form B, that has not being submitted, and ofcourse using a GET is not adviced.
Thanks for your time and patience.
It's not completely unheard of to do this. Quite often, a different parameter is passed in the form element's action attribute like /submit.php?action=register or /submit.php?action=activate.
So, you have code like this:
if ($_GET['action'] == 'register') {
// Register user
} else if($_GET['action'] == 'activate' {
// Activate user
}
However, you could also just change the value of the submit button and have the action attribute the same for both forms:
if (isset($_POST['submit'])) {
if ($_POST['submit'] == 'register') {
// Register user
} else if($_POST['submit'] == 'activate') {
// Activate user
}
}
create separate form_process script then include in form pages.
if(!empty($_POST)){
include 'form_process.php';
}
form_process.php should contain only class/function without echo or print out.
alternately you may set action url to the same page then redirect back to proper page.
<form id="add-profile-form" action="form_controller.php" method="post">
<input type="hidden" name="act" value="adding"/>
<!-- form 1. -->
</form>
<form id="edit-profile-form" action="form_controller.php">
<input type="hidden" name="act" value="editing"/>
<!-- form 2. -->
</form>
form_controller.php
if(isset($_POST['act']){
if($_POST['act'] == 'adding'){
//process form1
}else if($_POST['act'] == 'editing'){
//process form2
}
header("Location: success.php");
}
You can do it on the same page also. Just you need to make action same for both the forms.
You need to make some condition and write the individual functionality for Form A and for Form B depending on the source form.
You can check with the parameters in action like #Ami has used.
/submit.php?action=register or /submit.php?action=activate
So, you have code like this:
if ($_GET['action'] == 'register') {
// Register user
} else if($_GET['action'] == 'activate' {
// Activate user
}
However, you could also just change the value of the submit button and have the action parameter the same for both forms:
if (isset($_POST['submit'])) {
if ($_POST['submit'] == 'register') {
// Register user
} else if($_POST['submit'] == 'activate') {
// Activate user
}
}
I have a form setup but for some reason the JS to submit the form works in Chrome but not IE9 or Safari. Interestingly enough in Chrome where the submit button does work none of the information gets passed.
Here is my submit button -
<img type="submit" src="lib/send_feedback.jpg" border="0" class="feedback-submit-img" />
Here is what JS it calls
// Submit form to next page
function submitForm() {
// document.forms["feedbackform"].submit();
document.feedbackform.submit();
}
// Submit form and validate email using RFC 2822 standard
function validateEmail(email) {
// Modified version original from: http://stackoverflow.com/a/46181/11236
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// Return true if email field is left unchanged
function originalText(email){
var defaultMsg;
defaultMsg = "Enter your email address (optional)";
if(defaultMsg == email){
return true;
}
return false;
}
// Verify or decline with error message
function validate(){
$("#result").text("");
var email = $("#email").val();
if ((validateEmail(email)) || originalText(email)) {
submitForm();
} else {
$("#result").text(email + " is not a valid email.");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
For the second part of my issue which may or may not be related to the JS issue is -
echo $POST['satisfaction'];
echo $POST['user_email'];
echo $POST['comments'];
if(isset($POST['user_email'])){
echo 'true';
} else {
echo 'false';
}
If you would like a better look at the page I am editing here is a link to jsfiddle
edit
As per Marco's request I removed the link from around the submit button and placed the onClick event onto the actual button itself. This absolutely fixed the issue on both IE and Safari. Now my remaining question/concern is why the POST data is not passing correctly to the next page.
Here is the complete source with George requested. - index.php
Page source gets passed to - feedback-accept.php
Also with that being said/posted, what is StackOverflow's preferred site to post source to?
In response to Brian's comment, if I cannot use failed without potentially breaking the POST data, what would be a good alternative/work-around?
try this code:
jQuery:
$(document).ready(function()
{
$('.validate').bind('submit click',function()
{
//Validate!
//is email
if( /..../.test( $(this).find('input[name=email]').val() ) )
{
alert('Error!!!');
return false; //STOP PROPAGATION
}
//Its okay!
//send form!
$(this).parents('form').submit();
//click event stop propagation
return false;
});
});
HTML:
Submit
OR
<input type="submit" value="Submit" class="validate" />
OR
<button class="validate" >Submit</button>
In a quick look, I would say you are having a conflict of functions here. When you design a Submit Type, you are telling the browser that that will submit your form (on its action), on the other hand, that is inside a link that is calling a JS function. If you're manufacturing the submit in your JS, try to consider not use a Submit Type and see if it works more properly.
You might also try to replace the link for a simple "onSubmit" inside the form's Tag and call the JS function from there. This way, when the browser identifies that the user hit the submit button, he'll call a JS Function as you wish and if this function returns true, the submit will be allowed by the browser.