Pass PHP select option box values to another page - php

what i'm trying to doing is when user click on php select option.then
it's value should pass to another page as variable.
there is a code i'm
trying.
<table>
<tr><td>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("member")or die(mysql_error());
$result = mysql_query("SELECT id,ugroup FROM ugroups");
?>
<select name='group' id='group' >
<?php
while ($line = mysql_fetch_array($result)) {
echo '<option value=' . $line['ugroup'] . '>' . $line['ugroup'] . '</option>';
}?>
</select>
click
</td></tr>
</table>
this is add_group.php code
<?php
session_start();
ob_start();
include('../limoconfig.php');
if(!isset($_SESSION['adminuserid']) )
{
header('Location:../index.php');
}
else
{
if($_GET)
{
$ugroup = $_GET['ugroup'];
/*$id = $_GET['id'];*/
$acc_status = "update users set ugroup='".$ugroup."' where id=1931";
echo $acc_status;
$rate = db::getInstance()->exec($acc_status);
header('Location:../home.php');
}
}
?>
it's not working.

First of all you need to put your table within
and then you can call ajax on click of your anchor ().
jQuery(document).ready(function($) {
var data='';
$("#group option:selected").each(function() {
if ($(this).attr('value') !== '') {
data=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
type: "POST",
url: "file.php",
data: data,
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});

Wrap it in a form tag and create a submit button instead of the link and it can send it in either POST or GET.
The element is a form control and can be used in a form to collect user input.
http://www.w3schools.com/tags/tag_select.asp

you can either do it with ajax or just using html forms.
eg of ajax : Just a simple eg, you can modify according to your need
<html>
<head>
function myAjax(str)
{
if (str=="")
{
document.getElementById("results").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","add_group.php?ugroup="+str,true); // your next page
xmlhttp.send();
}
function myFunction() {
var x = document.getElementById("group").value;
myAjax(x);
}
</script>
</head>
<body>
<table>
<tr><td>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("member")or die(mysql_error());
$result = mysql_query("SELECT id,ugroup FROM ugroups");
?>
<select name='group' id='group' >
<?php
while ($line = mysql_fetch_array($result)) {
echo '<option value=' . $line['ugroup'] . '>' . $line['ugroup'] . '</option>';
}?>
</select>
click
</td></tr>
</table>
<div id="results"> <!-- the echo of add_group.php gets displayed here --> </div>
</body>
</html>

Related

Insert into DB with jQuery and get Feedback

I have a MySQL Database on a Server. This is how my HTML stores thing in that DB
var shV = localStorage.getItem("PersName");
var idV = localStorage.getItem("codeQR");
var posV = localStorage.getItem("position");
window.open('http://*.es/insert.php?sh='+shV+'&id='+idV+'&pos='+posV,
'blank','location=no,hidden=yes,closebuttoncaption=Done,toolbar=no');
The Insert.PHP File
<?php
try {
$pdo = new PDO('mysql:host=mysql.**');
$shortV = $_GET['sh'];
$idnumberV = $_GET['id'];
$positionV = $_GET['pos'];
$statement = $pdo->prepare("INSERT INTO idtabelle (short, idnumber, position)
VALUES (:sh, :id, :pos)");
$statement->execute(array('sh' => $shortV, 'id' => $idnumberV, 'pos' => $positionV));
echo "$idnumberV eingetragen";
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
?>
I want to store them without opening a new Page or show them the Insert Url. After it is in the DB i want a Feedback like "Your Data has been entered" only when they are really in the DB.
In an other HTML I search the Position by entering an ID in an Textfield. It works like I want. In the Page and a Feedback is given.
Search.html
<form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Get Position</button>
</form>
<div id="div1">Testing</div>
<div id="div2"> Here </div>
<script>
$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search3.php", $("#search").serialize(), function(d){
if (!$.trim(d)){
alert("Nothing found !"); }
else{
$("#div1").empty().append(d);
localStorage.setItem("PosGet",d);
document.getElementById("div2").innerHTML=(d);
}
});
});
});
The Search.PHP File
<?php
try {
$pdo = new PDO('mysql:host=mysql.**');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position, short FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
?>
How can I do it that the Insert is like the Search above in the Page and with a Feedback?
Thank you.
in your first example the code runs a new window (but hidden), so you have no chance to get a result from the inital window. You should do it like in the second provided example.
If you can use jQuery ( your examples looks like) you can use the jQuery.ajax() function
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
You also can have a success and a failure callback. Example:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
function(){
console.log("success");
},
function(){
console.log("error")
}
})
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$dbconn = pg_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect');
}
$query = "SELECT * FROM user WHERE id = $1";
$result = pg_prepare($dbconn, "my_query", $query);
$data = array($q);
$result = pg_execute($dbconn, "my_query", $data);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = pg_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
echo "</table>";
pg_close($dbconn);
?>
</body>
</html>
The Html
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
This is a simple example using PostgreSQL, for you to understand the basics. If you want more help start programming, and if you have any difficulties ask the community.
In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.
The function is triggered by the onchange event.
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and exit the function. If a person is selected, do the following:
1) Create an XMLHttpRequest object
2) Create the function to be executed when the server response is ready
3) Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a preaper execute on a PostgreSQL database, and returns the result in an HTML table.
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
1) PHP opens a connection to a PostgreSQL server
2) The correct person is found
3) An HTML table is created, filled with data, and sent back to the "txtHint" placeholder.

Display data on dropdown selection

I want to display data from database when I select an option from a dropdown option in php
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<?php
include("db_connection.php");
$name="select name from supplier_name";
?>
<form method="POST" action="getuser.php">
<tr>
<td>Name</td>
<td><?php echo "<select name='name'
onchange='showUser(this.name)'><option value=''>select
name</option>";
foreach ($con->query(#$name)as $ridyn)
{
echo "<option value='$ridyn[name]'>$ridyn[name]</option>";
}
echo"</select>"; ?></td>
</tr>
</form>
<br>
<div id="txtHint"><b>You have selected......</b></div>
</body>
</html>
Here is a jQuery example (I am not really familiar with straight javascript ajax). You should be able to fill it in from this example.
// Have a function that returns your names
function getSuppliers($con)
{
$query = $con->query("select `name` from `supplier_name`");
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
return (!empty($row))? $row : array();
}
// Include database con at top
include("db_connection.php");
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
// On menu-change
$(this).on('change','.ajax_change',function(e){
$.ajax({
// Get the url from the action on the form
url: $('#getUser').attr('action'),
// Get the value of the dropdown
data: { value: $(this).val() },
type: 'post',
success: function(response) {
// Print to the text-hint div
$('#txtHint').html(response);
}
});
});
});
</script>
</head>
<body>
<form method="POST" action="getuser.php" id="getUser">
<table>
<tr>
<td>Name</td>
<td>
<select name='name' class="ajax_change">
<option value=''>Select name</option>
<?php foreach(getSuppliers($con) as $ridyn) {
?> <option value="<?php echo $ridyn['name']; ?>"><?php echo $ridyn['name']; ?></option>
<?php }
?> </select>
</td>
</tr>
</table>
</form>
<br />
<div id="txtHint"><b>You have selected......</b></div>
</body>
</html>

depended dropdown list auto select value and load data

Hi i got 2 dropdown list (client and product) and 1 content data. The product dropdown list is depended from the choice in client dropdown list (i've already done that). The problem is i want the content data is autoloaded depend on the choice in product dropdown list.
Here is my code:
<script>
function filterClient(str) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("ProductOpt").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter_client.php?f=client&q="+str,true);
xmlhttp.send();
}
function filterProduct(str) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter_product.php?f=product&k="+str,true);
xmlhttp.send();
}
</script>
<table border='0' style='float: right'>
<tr>
<td>
<form>
<select name='ClientFilter' onchange="filterClient(this.value);">
<option value='0' style="text-align: center">--Filter by Client--</option>
<?php
$clientDL = mysql_query("SELECT * FROM `Client`");
while($client=mysql_fetch_array($clientDL))
echo "<option value='".$client['ClientID']."'>".$client['ClientName']."</option>";
?>
</select>
</form>
</td>
<td>
<form>
<select name='ProductFilter' id="ProductOpt" onchange="filterProduct(this.value);">
<option value='' style="text-align: center">--Filter by Product--</option>
</select>
</form>
</td>
</tr>
</table>
<div id="content"></div>
filter_client.php:
<?php
if (file_exists("../../../../wp-load.php")) {
require_once("../../../../wp-load.php");
}
$k = $_GET['k'];
global $dbhandle;//Database connection
if($q!=0) {
if (isset($_GET['f']) && $_GET['f'] == 'client') {
$productDL = mysql_query("SELECT * FROM `Product` where ProductID = " . $k);
while ($product = mysql_fetch_array($productDL))
echo "<option value='" . $product['ProductID'] . "'>" . $product['ProductName'] . "</option>";
}
}
?>
filter_product.php:
<?php
if (file_exists("../../../../wp-load.php")) {
require_once("../../../../wp-load.php");
}
$q = $_GET['k'];
global $dbhandle;//Database connection
if(isset($_GET['f'])&&$_GET['f']=='product'){
$result = mysql_query("SELECT * from `Invoice` WHERE ProductID= ".$k);
}
$list_Client = array();
while($row=mysql_fetch_object($result)){
$list_Client[] = $row;
}
// Load data from db and show it in div id = content
?>

Select data from mysql with PHP and Ajax

I want to fetch all the records by filtering a role from a dropdown list. This was working perfectly.
(1) But I want to display all the records by default, only when I select the role, all the role users should be filtered.
(2) I want to make my code shorten instead of writing the code two pages, could we fetch all the data from members.php, instead of using memlist.php again.
members.php
<html>
<head>
<script type="text/javascript" src="js/jqueryv1.10.2.js"></script>
<script type="text/javascript">
function showUser(str)
{
document.getElementById("getrole").style.display="block";
if (str =="")
{
document.getElementById("getrole").innerHTML="";
return;
}
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status == 200) { document.getElementById("getrole").innerHTML = xmlhttp.responseText; }
}
xmlhttp.open("GET","memlist.php?role="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo 'Select the role : <select name="users" onchange="showUser(this.value)">';
$sel_role = $db->query('SELECT * FROM role');
$sel_role->execute();
echo '<option selected="selected">Select a role</option>';
while ($row = $sel_role->fetch(PDO::FETCH_ASSOC))
{
$role_id = $row['role_id'];
$role_name = $row['role_name'];
echo '<option value='.$role_id.'>'.$role_name.'</option>';
}
echo '</select>';
echo '<div id="getrole"></div><input type="hidden" value='.$role_id.'>';
?>
</body>
</html>
memlist.php
<?php
require 'init.php';
$uid = $_GET['role'];
$dis_role = $db->prepare('SELECT bu.*, br.* FROM users bu JOIN role br ON bu.role_id = br.role_id WHERE br.id = '.$uid.'');
$dis_role->execute();
echo '<table id="result">
<tr><th><label>USERNAME</label></th>
<th><label>ROLE</label></th>
</tr>';
foreach($dis_role as $dr)
{
echo '<tr>
<td>'.$dr['username'].'</td>
<td>'.$dr['role_name'].'</td>
</tr>';
}
echo '</table>';
?>

Loading data from database with php and pure ajax in a textbox

i have one dropdown list which has data for "subjects" loaded from database. when i clicked on one subject what it should do is load related "subject_id" value inside textbox which is just below dropdown list option. i dont know how to bring value from getbook.php and show in book_ID input text.
show_bookid(str) {
var xmlhttp;
if (str.length == 0) {
document.getElementById("bookid").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
strong text
xmlhttp = new ActiveXOjbject("Microsoft.XMLHttpRequest");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("bookid").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getbook.php?q=" + str, true);
xmlhttp.send();
}
getbook.php
<?php
<?php
$b = $_GET['q'];
include('includes/security.php');
include('includes/dbconnect.php');
$database = new MySQLDatabase();
$sql = "select * from tbl_bkcat where book_id='" . $b . "'";
$result = mysql_query($sql);
?>
?>
below is the File where i need to bring value
<form name="bookadd" action="" class="jNice" method="post">
<p>
<label>Subject</label>
<select name="subject" onChange="show_bookid(this.value);">
<?php while($sel_rows=mysql_fetch_array($subresult)) { ?>
<option value="<?php echo $sel_rows['book_id'];?>">
<?php echo $sel_rows[ 'subject']?>
</option>
<?php } ?>
</select>
</p>
<p>
<label>Book_Id</label>
<input type="text" id="bookid" class="text-small" />//where i need to load subject id</p>
The mistake was done at ajax part document.getElementById("bookid").innerHTML and must be replaced with document.getElementById().value since I had to put data to Html Element that cotain value i.e Textbox(as textbox contain value attribute).
InnerHTML is used to manipulate the html elements that does not contain value,
** div,h1, ** etc. for details see below link.
http://www.verious.com/qa/what-39-s-the-difference-between-document-get-element-by-id-quot-test-quot-value-and-document-get-element-by-id-quot-tes/
ajax code
function show_bookid(str)
{
var xmlhttp;
if(str.length==0)
{
document.getElementById("bookid").value="";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp= new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXOjbject("Microsoft.XMLHttpRequest");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("bookid").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getbook.php?q="+str,true);
xmlhttp.send();
}
getbook.php
<?php
$b=$_GET['q'];
include('includes/security.php');
include('includes/dbconnect.php');
$database=new MySQLDatabase();
$sql="select * from tbl_bkcat where book_id='".$b."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
echo $row['Book_id'];
?>
addbook.php
<form name="bookadd" action="" class="jNice" method="post">
<fieldset>
<p><label>Subject</label>
<select name="subject" onChange="show_bookid(this.value);">
<?php
while($sel_rows=mysql_fetch_array($subresult))
{
?>
<option value="<?php echo $sel_rows['book_id'];?>">
<?php echo $sel_rows['subject']?>
</option>
<?php
}
?>
</select>
</p>
<p>
<label >Book ID</label>
<input type="text" id="bookid" name="book"/>
</p>
Your subject_id is not displaying because you have not printed your book_id after fetching results from database in getbook.php
After this $result=mysql_query($sql);
Write echo $result['your_book_id_field_name'];

Categories