php form should not refresh after validation - php

This is a Form I want to validate. The form has a select menu and if I select an option from the dropdown it shows two textboxes and an select menu. After submitting the form, the page refreshes and the form fields that I wanted to validate also hide.
What I want to do is validating the form without a page refresh.
Edited please note this: If i select other option that is IE,Safari except other option and submit the validation arise for that also
<html>
<head>
<style>
#browserother{display:none;}
.error
{
color:#F00;
}
</style>
<?php
$otherbrowser1="";
$otherbrowser1Err="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["ob1"]))
{
$otherbrowser1Err="* otherbrowser1 is Required";
$valid=false;
echo "<style>#browserother{display:block;}</style>";
}
else
{
$otherbrowser1=test_input($_POST["ob1"]);
}
//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "Browser" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "1") echo "selected"; ?>>IE</option>
<option value = "2" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "2") echo "selected"; ?>>FF</option>
<option value = "3" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "3") echo "selected"; ?>>Safari</option>
<option value = "4" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "4") echo "selected"; ?>>Opera</option>
<option value = "5" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "5") echo "selected"; ?>>Other</option>
</select>
</p>
<div id="browserother">
Please Specify: <label><input type="text" name="ob1" placeholder="Other Browser1" size="50" /></label>
<span class="error"><?php echo $otherbrowser1Err?></span>
<br>
Please Specify: <label><input type="text" placeholder="Other Browser2" size="50" /></label><br>
Please Specify: <label>
<select>
<option>Select an Option</option>
<option>Select an Option</option>
</select>
</label>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=Browser]').change(function(e){
if ($('p select[name=Browser]').val() == '5'){
$('#browserother').show();
}else{
$('#browserother').hide();
}
});
$('p select[name=OS]').change(function(){
if ($('p select[name=OS]').val() == 'otheros'){
$('#osother').show();
}else{
$('#osother').hide();
}
});
</script>
<!--currentstatus Ends here-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>

PHP basically refresh the page,You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.
you can use some code like this :
$('#form').validate(function(){
... your validation rules come here,
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
return false;
});
and in your html
<form id="jsform" method="post" action="">

It's difficult to understand what is the exact question.
Anyway I believe that you you don't want #browserother to be hidden in case of error ?
if so make sure that when you validate the form, add a display block for: #browserother
if(empty($_POST["ob1"]))
{
$otherbrowser1Err="* otherbrowser1 is Required";
$valid=false;
echo "<style>#browserother{display:block;}</style>";
}
Anyway very ugly code.
for dropdown:
<p>Chose Your Browser: <select name = "Browser" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "1") echo "selected"; ?>>IE</option>
<option value = "2" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "2") echo "selected"; ?>>FF</option>
<option value = "3" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "3") echo "selected"; ?>>Safari</option>
<option value = "4" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "4") echo "selected"; ?>>Opera</option>
<option value = "5" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "5") echo "selected"; ?>>Other</option>
</select>
</p>
I don't see any code for other cases, but to validate that field only when last option selected you should replace your code with this:
if ($_POST['Browser'] == 5) {
if(empty($_POST["ob1"]))
{
$otherbrowser1Err="* otherbrowser1 is Required";
$valid=false;
echo "<style>#browserother{display:block;}</style>";
}
else
{
$otherbrowser1=test_input($_POST["ob1"]);
}
}
which means to ask for validation of ob1 field only when last value is selected.

If you wish to check validation before submission of form and after validating all fields you wish to submit form, then instead "onclick" event of button, write a submit event of form or click event of button.
Inside that event check validation and then submit your form. If any field is invalid then return it from there only.

Upon submitting the form the page refreshes, either use AJAX as said above or in your inputs that you want to be saved type
<input type="text" name="whatever_name" value="<?php if (isset($_POST['whatever_name'])) echo $_POST['whatever_name'];?>" />
This way when you submit the data that was submited will be in the form "value" attributes.
But I would advise using ajax, as it's more clean.

PHP form will refresh once you click submit button.So please do validation in javascript or jquery and after that use php for getting form values.
Remove onclick from submit button and add id and name attr to it
$("#submitbuttonid").click(function(e){
if($('input[name^=ob1]').val() == "")
{
alert("Other browser is req.");
return false;
}
});

Your code was pretty cluttered I don't even know where to begin. Your validation had logical flaws, you were mixing HTML and PHP kinda strangely and so on. I felt free to rewrite it a little bit and I added the feature you asked for.
Normally I don't do this but I want to show you a cleaner way to do such kind of tasks for the future. Of course this isn't the ideal way either (stuffing evertything into a single file is not the best practice as you may know).
For your understanding I commented everything. But basically we are sending an ajax request to the script. The script validates our form and returns a json response. This is a neat way to manage data between client and server.
The redirection process then takes place on the client side and redirects the user if everything was okay.
Please note that I did not do any security checks here
<?php
// Just a helper function to check if a form field is set and filled
function fieldSet($field)
{
return isset($field) AND !empty($field);
}
// Our dropdown will be generated from that array
$browsers = array('IE', 'FF', 'Safari', 'Opera', 'Other');
/**
* Lets process this when a POST Request came in
*/
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// Set JSON Header
header('Content-Type: application/json');
// Prepare our response
$response = array('success' => false);
// Reassign POST variables just to make it look prettier
$browser_select = $_POST['browser'];
$specifications = $_POST['specify'];
// If a browser has not been selected the user failed hard!
if(!fieldSet($browser_select) OR $browser_select == 'init')
$response['errors'][] = 'Please Select a browser';
// If we selected 'other' check if the hidden form group has any input
// and push an error to our $response array if not
if($browser_select == $browsers[4] AND (!fieldSet($specifications) OR $specifications[2] == 'init'))
$response['errors'][] = 'Another Browser is required';
// If we got no errors in our $response array the request was successful
if(!isset($response['errors']))
$response['success'] = true;
// Encode our $response array into the JSON format and
// abort script execution
echo json_encode($response);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Ajax Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form action="cleanform.php" method="POST" id="ajax-form">
<label for="select-browser">Choose your Browser</label>
<option value="init">Please select a browser</option>
<select name="browser" id="select-browser">
<?php foreach($browsers AS $browser): ?>
<option value="<?php echo $browser; ?>"><?php echo $browser; ?></option>
<?php endforeach; ?>
</select>
<hr>
<div id="hidden-field-group" style="display: none;">
<label for="specify-1">Please Specify</label>
<input type="text" name="specify[]" placeholder="Other Browser 1" id="specify-1">
<br>
<label for="specify-2">Please Specify</label>
<input type="text" name="specify[]" placeholder="Other Browser 2" id="specify-2">
<br>
<label for="specification-3">Please Specify</label>
<select name="specify[]" id="specify-3">
<option value="init">Please Specify</option>
<option value="SP 1">SP1</option>
<option value="SP 2">SP2</option>
</select>
</div>
<input type="submit">
</form>
<script type="text/javascript">
$(function(){
var $form = $('#ajax-form');
var $browserSelect = $form.find('select[name="browser"]');
// Hide or Show the second form group
$browserSelect.on('change', function(){
$select = $(this);
if($select.val() == 'Other'){
$('#hidden-field-group').show();
}
else{
$('#hidden-field-group').hide();
}
});
// Here we send a POST Request to the server using AJAX
$form.on('submit', function(e){
// Prevent the browser from submitting the form
// in it's native way
e.preventDefault();
$.ajax({
type: 'POST',
url: $form.action,
data: $form.serialize(), //Serialize our form fields
success: function(response)
{
// Redirect if the server returned no error
if(response.success == true)
window.location.replace("http://example.com");
//otherwise print the error
else
alert(response.errors[0]);
}
});
});
});
</script>
</body>
</html>

Related

How to repopulate multiple select boxes and checkboxes

I cannot find a way that works to re-populate multiple select boxes, Since it is stored as an array is there a way to cross-check and repopulate the selections that were made? I am trying to answer question 4 from the comments section of the code.
The section of the form that I am trying to repopulate is the like_bands multiple select box
my code:
<?php
session_start();
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
$load_date = $_COOKIE['load_date'];
$is_cool = $_POST['is_cool'];
var_dump($is_cool);
$bands = $_POST['like_bands'];
$band_list = "";
foreach ($bands as $band) {
$band_list .= $band. ", ";
}
$other_band = $_POST['other_band'];
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['bands'] = $band_list;
$_SESSION['other_band'] = $other_band;
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<?php if ($is_cool != null) {?>
<input type="checkbox" name="is_cool" value="yes" checked='checked'>
Are you cool?
<?php } else { ?>
<input type="checkbox" name="is_cool" value="yes">
Are you cool?
<?php }?>
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath">Black Sabbath</option>
<option value="Mastodon">Mastodon</option>
<option value="Metallica">Metallica</option>
<option value="Swift">Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit"> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
/*if (isset($_POST['like_bands'])) {
header('Location: hw_page2.php');
}*/
?>
</body>
</html>

Re-populate fields after form submission and redirection PHP ONLY

I am supposed to have my form elements repopulate using php and html only after I click the link from page two. However, none of the fields are repopulating. Please help me!!?
Page 1:
<?php
session_start();
?>
<?php
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<?php
$load_date = $_COOKIE['load_date'];
$_SESSION['is_cool'] = $_POST['is_cool'];
$_SESSION['like_bands'] = $_POST['like_bands'];
$_SESSION['other_band'] = $_POST['other_band'];
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
print_r($bands);
echo $other_band;
echo $is_cool;
?>
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value= "yes" <?php if ($is_cool == 'yes') {
echo 'checked = "yes"';
}?>>
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?>> Black Sabbath</option>
<option value="Mastodon" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?> >Mastodon</option>
<option value="Metallica" <?php if (isset($_SESSION['like_bands']) && in_array("Metallica", $bands)) {
echo 'selected';
} ?> >Metallica</option>
<option value="Swift" <?php if (isset($_SESSION['like_bands']) && in_array("Swift", $bands)) {
echo 'selected';
} ?> >Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit" name= 'submit' value = 'submit'> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
echo $_SESSION['is_cool'];
if (isset($_SESSION['like_bands'])) {
header('Location: hw_page2.php');
}
?>
</body>
</html>
My second Page:
<?php
session_start();
/*
This page should:
1) Transfer back to hw_page1.php if loaded directly without the survey being completed (no survey data in session).
2) Display the Survey Data submitted from the previous page.
3) The form in this page should submit to THIS PAGE.
Use PHP to validate that the form below is completed.
Validate that the signature is not the empty string or only blank spaces (use PHP trim() function)
And of course validate that the checkbox was checked.
If the validation passes, save the signature into SESSION ande transfer to hw_page3.php.
If the validation fails, don't transfer.
Instead, back through to the form in this page WITH an appropriate message.
In that case, the Survey Data MUST also re-display in this page.
Note:
hw_page1.php used client-side JavaScript validation to ensure that all data was collected.
For the form below. do NOT use client-side JavaScript validation, but rather use PHP as instructed above.
Client-side validation is convenient for the end user, but can be bypassed by someone with know-how.
*/
?>
<?php
if (!isset($_SESSION['is_cool']) and !isset($_SESSION['like_bands'])) {
header('Location: hw_page1.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Verify Profile</title>
</head>
<body>
<?php
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
echo $is_cool;
print_r($bands);
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
$bandslist = "";
foreach ($bands as $band) {
$bandslist .= "$band, ";
}
?>
<!-- Display Survey Data Here -->
<table width="" border="1" cellspacing="0" cellpadding="5">
<tr valign="top">
<td>Are you cool?</td>
<td>Liked Bands</td>
<td>Other Favorite Band</td>
</tr>
<tr valign="top">
<td><?= $_SESSION['is_cool']; ?></td>
<td><?= $bandslist; ?></td>
<td><?= $other_band; ?></td>
</tr>
</table>
<br><br>
<form action="hw_page2.php" method="GET" >
Verify that your profile data shown above is accurate by signing below.
<br>
<input type="text" name="signature" value="" placeholder="Sign Here">
<br>
<input type="checkbox" name="user_certify" value="yes">
I certify, under penalty of purgery, that my profile is accurate.
<br><br>
<button type="button" onclick="window.location='hw_page1.php';"> Go Back: Edit Profile Before Signing </button>
<!-- This is NOT a Submit Button! -->
<br>
<button type="submit"> Record Profile </button>
<!-- This is obviously -->
</form>
</body>
</html>
Please help me figure out where I am making a mistake! I have been working on it for days but I cannot figure out the answer.

Refresh a PHP page after checking/unchecking a checkbox

I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()

Why won't the HTML select form element $_POST multiple values in PHP?

if (isset($_POST['ids']) && $_POST['ids'] === 'ford') {
echo "yah!!!";
print_r($_POST);
$filename = "ford.txt";
} elseif (isset($_POST['ids']) && $_POST['ids'] === 'toyota') {
print_r($_POST);
} elseif (isset($_POST['landrover']) && $_POST['ids'] === 'landrover') {
} elseif (isset($_POST['algonquin']) && $_POST['ids'] === 'algonquin') {
} elseif (isset($_POST['errors']) && $_POST['ids'] === 'errors') {
}
testing to see if $_POST superglobal array is posting. It is only posting one value 'ford'. Not sure why none of the other values aren't posting.
<form name="form" method="post" action="<?php echo $filename; ?>" target="box" >
<select name="ids">
<option value="ford">Ford</option>
<option value="toyota">Toyota</option>
<option value="landrover">Land Rover</option>
<option value="algonquin">Algonquin</option>
<option value="errors">Errors</option>
</select>
<input type="submit" name="submit" value="View File" />
</form>
This is the form with all of the options and their values. It has a variable $filename which links to a text file which is meant to be opened in a target box. The if statement above is supposed to determine what file to open.
<iframe src="" name="box" width="100%" height="100%" frameborder="0"></iframe>
The iframe or target box the file is supposed to open in.
If you wish to POST multiple values from your <SELECT>, you will need to make a few modifications.
Let's start with your form...
<form name="form" method="post" action="selections.php" target="box" >
<select name="ids[]" multiple>
<option value="ford">Ford</option>
<option value="toyota">Toyota</option>
<option value="landrover">Land Rover</option>
<option value="algonquin">Algonquin</option>
<option value="errors">Errors</option>
</select>
<input type="submit" name="submit" value="View File" />
</form>
<iframe name="box" width="100%" height="100%" frameborder="0"></iframe>
Your form will need to be received by a .php file, not a .txt file. I'm not sure what you are trying to do with $filename.
If you want to allow multiple selected options on your form, make the name value an array like: ids[] and write multiple inside the <select>.
If you don't need the submit value on your POST receiving file, then you don't need to write a name attribute on <input type="submit">
On your submission receiving page (let's call it selections.php), the `$_POST array can look like the following:
If you selected Ford, then:
$_POST=array('ids'=>array('ford'),'submit'=>'View File');
If you selected Toyota and Errors, then:
$_POST=array('ids'=>array('toyota','errors'),'submit'=>'View File');
If no selections are made, then :
$_POST=array('submit'=>'View File');
To check this SUPERGLOBAL data, you can use the following:
<?php
if(!isset($_POST['submit'])){
echo "No submission data";
}elseif($_POST['submit']=='View File'){
echo "Invalid/Unexpected submit data";
}elseif(empty($_POST['ids'])){
echo "No ids selected";
}else{
$valid_ids=['ford','toyota','landrover','algonquin','errors'];
$_POST['ids']=array_intersect($_POST['ids'],$valid_ids); // validate
foreach($_POST['ids'] as $id){
// do whatever you like with $id , perhaps $filename=$id.".txt" or something
}
}
This is presumably happening because you're not checking the $_POST['ids'] value in the following if conditions. I would wager that if you selected 'toyota' it would work.
This is what your code should look like
if (isset($_POST['ids']) && $_POST['ids'] === 'ford') {
echo "yah!!!";
print_r($_POST);
$filename = "ford.txt";
} elseif (isset($_POST['ids']) && $_POST['ids'] === 'toyota') {
print_r($_POST);
} elseif (isset($_POST['ids']) && $_POST['ids'] === 'landrover') {
print_r($_POST);
} elseif (isset($_POST['ids']) && $_POST['ids'] === 'algonquin') {
print_r($_POST);
} elseif (isset($_POST['ids']) && $_POST['ids'] === 'errors') {
print_r($_POST);
}
Edit:
as mentioned above, it seems like you're implying that the form should go to ford.txt?

Jquery form submit with PHP

I need help with what I thought would be a simple form submit problem with Jquery, but am running into issues.
I have a form, #listing_step_1, in which the user first selects a category from a dropdown. When a category has been selected, if the user clicks "next", the subcategory dropdown is revealed. When both a category and subcategory is selected, clicking next will take them to step 2 of the process using a redirect. On submission, the form is reloading the same page using $_SERVER['PHP_SELF'].
I want to autosubmit the form so clicking on next is not required to reveal the subcategories. I'm trying to do this on an onchange event using JQuery, but the following code does not work.
$('#item_category').change(function(){
$('#listing_step_1').submit();
});
I would appreciate any help with this as I am new to form submission using JQuery and AJAX. Manually, it's working fine - i.e., pressing the page button and with the PHP page refresh. I thought by simply submitting the form in the onchange instance it would reload and execute the required actions, but this does not appear to be the case.
Form code:
<form method="post" name="listing_step_1" id="listing_step_1" action="<?php $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data" <?php if($errormessage != ""){ echo ' style="margin-top: 30px"';}?>>
<div class="formField fullwidth">
<label for="item_category">Category *</label>
<select id="item_category" name="item_category">
<option value="0">Select category...</option>
<?php $cd = new CategoryListing("<option_credits>", "</option>"); ?>
</select>
</div>
<div class="formField fullwidth">
<label for="item_subcategory">Subcategory*</label>
<?php if($dropdownlist != "") { ?>
<select id="item_subcategory" name="item_subcategory">
<?php echo $dropdownlist; ?>
</select>
<?php } else { ?>
<select id="item_subcategory" name="item_subcategory" disabled="true">
<option value="0">Select subcategory...</option>
</select>
<?php } ?>
</div>
<input type="submit" value="Next" id="submit" name="submit" style="width: 100px;" />
</form>
Form Submission:
if(isset($_POST['submit'])){
if($_POST['item_category'] != 0){
$dropdownlist = CategoryListing::getSubCategoryDropdown($_POST['item_category']);
}
else {
$errormessage = "Please select a category";
}
}
Jquery:
$(document).ready(function(){
$('#item_category').change(function(){
this.form.submit();
});
});
Try this instead:
$(function() {
$('#item_category').change(function(){
this.form.submit();
});
});
in your description, you say:
I have a form, #listing_stage_1, in
which the user first selects a c...
then in code you say:
$('#item_category').change(function(){
$('#listing_step_1').submit();
});
I imagine you are just using the wrong selector... change your code to this:
$('#item_category').change(function(){
$('#listing_stage_1').submit();
});

Categories