refresh the page without redirecting - php

I have a search form like this in a file form.php. It works great, the problem I am facing is that I use class/methods(functions). For example I have this method that calls logo and manu bar.
//$this->output is just a method that echos, that's all it does
function header()
{
$this->output('<DIV CLASS="header">');
$this->logo();
include('form.php');
$this->links();
$this->header_clear();
$this->output('</DIV>');
}
Like the above, the form shows perfectly, but when I choose a category it takes me to form.php, and it ruins everything. (form.php is just a form)
I know the problem is here
onChange="javascript:this.form.action='form.php';
this.form.submit()
Without javascript I couldn't get the category values, the page is not refreshing, so $_POST['cat'] is empty.
What is a better way to refresh the page without taking me to different one?
I know probably this all confusing, just bear with me.
<form enctype="multipart/form-data" name="form" id="form" action="form.php"
method="get">
<SELECT name="cat" onChange="javascript:this.form.action='form.php';
this.form.submit()">
<option value="" >Categories</option>
<?php
$z = "0" ;
//Select categories form database
$category =db_select_categories($z);
if(is_array($category))
{
foreach($category as $rowc)
{
$id_cat = htmlentities($rowc['id_cat'], ENT_QUOTES);
$cat_name = htmlentities($rowc['cat_name'], ENT_QUOTES, 'utf-8');
$cat_name = stripslashes($cat_name);
echo "<option style=\"background-color:#FFCC99\" disabled>".$cat_name."
</option>";
$categories = db_select_categories($id_cat);
if(is_array($categories))
{
foreach($categories as $row)
{
$id = htmlentities($row['id_cat'], ENT_QUOTES);
$name = htmlentities($row['cat_name'], ENT_QUOTES, 'utf-8');
$name = stripslashes($name);
if ( $cat == $id )
{
echo "<option value='".$id."'selected> ".$name."</option>";
}
else
{
echo "<option value=".$id."> ".$name."</option>";
}
}
}
}
}
echo "</SELECT>";
?>
<div>
<?php
if(!empty($cat))
{
//Outputs a populated select option depending on category
display_search_options($cat);
}
?>
</div>

If you don't want it to go to form, just make it go somewhere else...
onChange="javascript:this.form.action='index.php';
this.form.submit()

Related

Catching the selected option's value

I want to pass a select option value through hyperlink to the next page and for this I have this code:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<form name="search_form" role="form" method="GET" id="search_form" action="SearchResults.php">
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM attributes WHERE attributename='mushtype'");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select id="mushtype" name="mushtype">
<option value="*" selected>Mushroom types</option>
<?php foreach($data as $row): ?>
<option value="<?php echo $row['idattributevalue']; ?>"><?php echo $row['attributevalueEN']; ?></option>
<?php endforeach; ?>
</select>
<?php
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Find Your Mushroom
</form>
</body>
</html>
For the default selected option I want to use (*) as value because if no option are selected, will stand as SELECT (all) FROM for my SQL query on the second page.
So, i tried to construct my hyperlink, but i don't know how to catch the selected option.
I tried to adapt from here
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['Movies'])) {
$selected = $_POST['Movies'];
echo 'You have chosen: ' . $selected;
} else {
echo 'Please select the value.';
}
}
?>
but I'm unable to do it.
Rigth now, my code inserting a value, but is without any control upon it.
Please help me to catch the selected option and insert it as value in my hyperlink. Thank you.
When you use <a>, you do not submit the inputs to the next page. Instead of
Find Your Mushroom
simply use
<input type="submit" value="Find Your Mushroom">
before closing the form.
Edit:
Depending on the <form method= you use ("get" or "post"), you will then either have $_GET['mushtype'] or $_POST['mushtype'] available in the next page. (Thanks to #ADyson!)
In my tests using method="get", the form inputs make their way to $_GET, but my uri parameters were not there. Using method="post" gave me both my uri parameters in $_GET and form details in $_POST, just in case you want to use both.
If you do not like the button style however, you can change it using CSS to look just like a regular hyperlink.

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()
})
})()

How do I keep the parameters on the URL (HTML GET) without duplicating them?

I'm trying to implement a simple multi-language form in HTML. The form has buttons that open database tables in a div, and also has a select to choose the language.
The buttons are like:
<button type='submit' name='table' value='x'>
The select is like:
<select name='lang' onchange='changeLang()'>
...
function changeLang() {
document.getElementById('form1').submit();
}
When I click a button, it shows the table (and a parameter like 'table=x' shows in the URL). But when I change the language, only the 'lang=y' parameter shows, the 'table' parameter disappears.
I tried the solutions here, here and here, but it's not working. The hidden parameters add to the existing button and I get two 'table' parameters on the URL. How can I keep all the parameters on the URL without duplicating them?
EDIT: I was trying to do something on this line:
<?php session_start();
$erroConn = include(".../dbfile.php");
if (isset($_GET['lang'])) { // language
$lang = $_GET['lang'];
leDic($lang);
} else {
$lang = NULL;
}
if (isset($_GET['table'])) { // table
$table = $_GET['table'];
} else {
$table = NULL;
}
if (isset($_GET['people'])) { // people
$people = $_GET['people'];
} else {
$people = NULL;
}
?>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>Example</title>
<script type='text/javascript'>
function changeLang() {
document.getElementById('form1').submit();
}
</script>
</head>
<body>
<form id="form1" name="form1" method="get" action="">
<h1>titulo</h1>
<?php
if (is_null($table)) {
echo "<button type='submit' name='table' value='0'>tabelas</button>"; # only shows the button if not yet pressed
} else {
echo "<input type='hidden' name='table' value='$table' />"; # if pressed keep the variable (but is doubling it?)
$people = NULL;
}
if (is_null($people)) {
echo "<button type='submit' name='people' value='0'>people</button><BR>";
} else {
echo "<input type='hidden' name='people' value='$people' />"; # if pressed keep the variable (but is doubling it?)
$table = NULL;
}
echo "<input type='text' name='msg' />";
echo "<input type='submit' value='ok' />";
$dir1 = glob('./coisas_txt*'); # all languages available as simple txt (key=value)
echo "<div id='langs' class='langs'>"; # class to make the language bar float
echo "<select name='lang' onchange='changeLang()'>";
foreach ($dir1 as $fname) {
$sigla = mb_substr($fname,-2,NULL,'UTF-8');
if ($sigla == $lang) {
echo "<option value='$sigla' selected>$sigla</option>";
} else {
echo "<option value='$sigla'>$sigla</option>";
}
}
?>
</select>
</div>
</div>
<div id='table'> <!-- where the table goes -->
<?php
if ($table !== NULL) {
}
?>
</div>
</form>
</body>
</html>
Hidden fields should work.
For each table have a form element with hidden input for the tables unique id and a select for languages.
For Example:
<form id="form1" name="form1">
<input type="hidden" id="table_1" name="table_1" value="x" />
<select id="lang" name='lang' onchange='changeLang()'>
</form>
<form id="form2" name="form2">
<input type="hidden" id="table_2" name="table_2" value="x" />
<select id="lang" name='lang' onchange='changeLang()'>
</form>
And have the changeLang function submit the form it's in only.
Native DOM elements that are inputs also have a form attribute that points to the form they belong to so this should work. Just find the parent of the input that calls the JavaScript function in your JavaScript. Might be able to use closest here as well. Play with it.
function changeLang() {
var form = ______.form;
form.submit();
}
Then interpret the $_GET['table'] AND $_GET['lang'] variables using PHP to decide what to show.
Like so:
<?php
//switch based on language...
switch($_GET['lang']){
case 'lang1':
//display table_1 if we should
if($_GET['table_1']){
?>
<!-- table_1 display in lang1 HTML here. -->
<?php
}
//display table_2 if we should
if($_GET['table_2']){
?>
<!-- table_2 display in lang1 HTML here. -->
<?php
}
break;
case 'lang2':
//display table_1 if we should
if($_GET['table_1']){
?>
<!-- table_1 display in lang2 HTML here. -->
<?php
}
//display table_2 if we should
if($_GET['table_2']){
?>
<!-- table_2 display in lang2 HTML here. -->
<?php
}
break;
default
//display table_1 if we should
if($_GET['table_1']){
?>
<!-- table_1 display in default lang HTML here. -->
<?php
}
//display table_2 if we should
if($_GET['table_2']){
?>
<!-- table_2 display in default lang HTML here. -->
<?php
}
break;
}
?>
Something like that.
Hope it helps!

return data from php dropdownlist after submit

hey guys i've passed way more time on this then what i originally wanted to...
so i have this code here, where i have a drop list give me data from a sql database from the selection of 3 radio buttons, that all works fine.
My problem come when i want to submit my form and get info of the data in said droplist. all i want is put the selected radio and the selected item in the single drop list in variables in the submission.php that comes after the post method of the form...
anyway thats what i want to do for now
<?php
require "../Scripts/config.php"; // database connection here
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>test</title>
<SCRIPT language=JavaScript>
function reload()
{
for(var i=0; i < document.form1.type.length; i++){
if(document.form1.type[i].checked)
var val=document.form1.type[i].value
}
self.location='bob.php?type=' + val ;
}
</script>
</head>
<body>
<?Php
$tp=$_GET['type']; // getting the value from query string
if(strlen($tp) > 1){$sql="SELECT * FROM Subcategory where cat_id='$tp'";}
echo $sql;
echo "<form name=form1 id=form1 method=post action=submissions2.php>";
echo "<select name=Subcategory id=Subcategory value=''>Subcategory</option>"; // printing the list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[cat_id]>$row[Subcategory]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box
echo "<br>";
echo "<br>";
echo "<br>";
echo "
<b>Type</b>
<input type=radio name=type value='1_Cosplay' onclick=\"reload()\";>Cosplay
<input type=radio name=type value='1_Modeling' onclick=\"reload()\";>Modeling
<input type=radio name=type value='1_Zombie' onclick=\"reload()\";>Zombie
<input type=submit value=Submit> </form>";
echo "<br>";
echo "<br>";
echo "<br>";
?>
</body>
</html>
and this is the submissions2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../Scripts/jquery-1.8.0.min.js"></script>
</head>
<body>
<?php
function filter($data) {
/*$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);*/
return $data;
return $row;
}
foreach($_POST as $key => $value) {
$mydata[$key] = filter($value);
}
echo $mydata['Subcategory'];
echo "<br>";
?>
</body>
</html>
all i seem to be able to get is the radio button choice.
Here is an all-in-one solution. You need to change some references like what the name/local path of the file path is, but anyway, this contains all the code. I can not test the DB stuff but the ajax works if you have the correct url path in the jQuery portion. Note, this solution references itself, not a new page:
// Display errors for troubleshooting
ini_set('display_errors','1');
error_reporting(E_ALL);
class CategorySelector
{
public function LoadSubCat()
{
// You will be subjected to an injection hack if you don't filter or encode this variable
// You should do PDO with prepared statements
$parent_cat = htmlspecialchars($_GET['parent_cat'], ENT_QUOTES);
$query = $this->Fetch("SELECT id,subcategory_name FROM subcategories WHERE categoryID = '$parent_cat'");
// Uncomment this to see how this returns
// $this->PrintPre($query); ?>
<label for="sub_cat">Sub Category</label>
<select name="sub_cat" id="sub_cat">
<?php
if($query !== 0) {
foreach($query as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subcategory_name']; ?></option>
<?php
}
} ?>
</select>
<?php
}
public function Form()
{
// Get rows for categories
$results = $this->Fetch("SELECT id,category_name FROM categories");
// Uncomment this to see how this returns
// $this->PrintPre($results); ?>
<form name="form1" id="form1" method="post">
<label for="parent_cat">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php
if($results !== 0) {
foreach($results as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php }
} ?>
</select>
<!-- This is a container that will load in your next menu -->
<div id="sub_cat_container"></div>
<input type="submit" name="submit" value="submit" />
</form>
<?php
}
public $rowCount;
// This is strictly a returning engine for SQL statements
protected function Fetch($_sql)
{
include_once('config.php');
// You really should do prepared statements (PDO)
// This way of calling sql is depricated
$query = mysql_query($_sql);
// Save the row count
$this->rowCount = mysql_num_rows($query);
// If there are rows return them
if($this->rowCount > 0) {
$_array = array();
// Loop through
while($result = mysql_fetch_array($query)) {
$_array[] = $result;
}
}
// Send back your query results for processing
// If no results, return false/0
return (isset($_array))? $_array:0;
}
protected function PrintPre($_array)
{ ?>
<pre>
<?php print_r($_array); ?>
</pre>
<?php
}
}
// Uncomment this for testing that the AJAX is working.
// print_r($_REQUEST);
// This is probably not the best way to do this all, but for sake
// of trying to get it all to work, this whole thing will ajax to
// itself, but if you can get it to work on this one page, you
// can split it up into two pages.
// Ok, so this creates a new instance of this whole system
$builder = new CategorySelector();
// If this page receives a GET request for $_GET['parent_cat'], just process it.
// That action is to call the sub_cat dropdown menu from this object
if(isset($_REQUEST['parent_cat']) && !empty($_REQUEST['parent_cat'])) {
$builder->LoadSubCat();
}
// If there is no request, display the html page
else {
// You should not have space before the <!doctype>. Some browsers act funky if there is space before
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
// I'm not a javascript person, so this portion is kind of sloppy
$(document).ready(function(){
$('#parent_cat').change(function() {
// Get value
var ElmVal = $('#parent_cat').val();
$.ajax({
// You need to reference this page in the "thispage.php" whatever this page is called
url:"/thispage.php?parent_cat="+ElmVal,
success:function(result) {
$("#sub_cat_container").html(result);
}});
});
});
</script>
</head>
<body>
<?php
// Display the form.
$builder->Form(); ?>
</body>
</html>
<?php } ?>
Quote all your HTML attributes like name='Subcategory', and
echo "<option value=$row[cat_id]>$row[Subcategory]</option>"
should be
echo "<option value='{$row['cat_id']}'>{$row['Subcategory']}</option>";
Your coding practice is horrible, by the way. You are not testing to see how many rows you have in your MySQL query, and you don't need to echo on each line. You can do this:
echo '<br />'.
'<br />';
Of course, using line breaks like that is a bad practice, as well. Use CSS.

Transfering the form data to more than one page using php

I have created one textfield and one dropdownlist and a button in my "index.php" page as follows:
<form value="indexform" action="" method="post">
<b>Number:</b><input type="text" name="number"/><br/>
<b>Network:</b>
<select name="network">
<option selected="">please...</option>
<option value="1">Bsnl</option>
<option value="2">Idea</option>
</select>
<input type="submit" name="proceed" value="submit">
</form>
and i have used the php code as follows for the above form:
<?php
if(isset($_POST['network']) && isset($_POST['number']))
{
$number = $_POST['number'];
$network = $_POST['network'];
}
if(!empty($_POST['network']))
{
switch($network)
{
case "1":header("Location:Bsnl.php");break;
case "2":header("Location:Idea.php");break;
default:exit();
}
?>
and i have crated two pages "Bsnl.php" and "Idea.php" Based on the selection taken in the dropdownlist the page will be redirected into either Bsnl/Idea.php
I have created the Bsnl/Idea.php page containg one textfield and submit button the code is as follows:
<form value="Bsnlform action="default.php" method="post">
<b>Amount:</b><input type="text" name="amount"/><br>
<input type="submit" value="submit">
</form>
php code is as follows:
<?php
if(!empty($_POST['amount']))
{
$amount = $_POST['amount'];
}
?>
atlast i want to print the entire form details(indexform as well as Bsnl/idea form) on the default.php page can any one help me how to do to print the values on default.php upto now i have tried the php code as follows:
<?php
echo $amount;
echo $network;
echo $number;
?>
First off, you need to enable session_start();
and change to this like so....
<?php
//Enable session first
session_start();
//Flush any existing session variables, you can choose where/if you wanna do this
session_unset();
if(isset($_POST['network']) && isset($_POST['number']))
{
$_SESSION['number'] = $_POST['number'];
$_SESSION['network'] = $_POST['network'];
}
if(!empty($_POST['network']))
{
switch($_SESSION['network'])
{
case "1":header("Location:Bsnl.php");break;
case "2":header("Location:Idea.php");break;
default:exit();
}
?>
Then change this to this....
<?php
//Session enable again
session_start();
if(!empty($_POST['amount']))
{
$_SESSION['amount'] = $_POST['amount'];
}
?>
Then in your next file....
<?php
session_start();
echo $_SESSION['amount'];
echo $_SESSION['network'];
echo $_SESSION['number'];
?>
Of course on your other page you wont echo $_SESSION['amount'], because it wont be set yet...

Categories