Display data on dropdown selection - php

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>

Related

Ajax in PHP5 - update drop down list with other drop down list

I'm trying to update drop down list with the other drop down list using Ajax. Somehow it is not working. I'm not sure which path is going wrong.
php file
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function AjaxFunction(cat_id)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
var myarray=eval(httpxml.responseText);
for(j=document.testform.subcat.options.length-1;j>=0;j--)
{
document.testform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd2.php";
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<title>tresn</title>
</head>
<table width="1021" border="0" style="top:0;left:0; position:fixed">
<tr>
<td height="25"><form action='Test3.php?mula=0&akhir=12' method="POST" class="dropdown_button" name="testform" id="form1">
<strong>
Sort By:
<select name="cat" onchange="AjaxFunction(this.value);" id="SortBy">
<option value="0">(Short By)</option>
<?php
$q=mysqli_query($db,"select * from db_prd_category ");
while($n=mysqli_fetch_array($q)){
echo "<option value=$n[Cat_Id]>$n[Name]</option>";
}
?>
</select>
<select name="subcat">
</select>
<input type="submit" class ="small button yellow" name="Filter" id="Filter" style="height:25px" value="Filter" />
</strong>
</form></td>
</tr>
</table>`
Ajax file
<?php
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysqli_query($db,"Select * from db_prd_subcategory where Cat_Id='$cat_id' ORDER BY SubCat_Id ASC");
echo mysqli_error();
$myarray=array();
$str="";
while($n=mysqli_fetch_array($q)){
$str=$str . "\"$nt[Name]\"".",";
}
$str=substr($str,0,(strLen($str)-1));
echo "new Array($str)";
?>

How do I put the result of Ajax (get data from server) into input tag?

See my picture:
I want that result be filled into an input tag.
It works if I do like this:
<?php
include('c2gcon.php');
include('logincheckadmin.php');
$nameajax=isset($_REQUEST['nameajax'])?$_REQUEST['nameajax']:null;
if($nameajax<>null){
$username=$nameajax;
$_SESSION['simpanun8']=$_SESSION['simpanun8'].','.$username;
$_SESSION['simpanun8'][0]='';
echo "username=$_SESSION[simpanun8]";
exit;
}
?>
<html>
<head>
<title>DELETE RECORD</title>
<link rel="shortcut icon" href="http://c2gdragonteam.com/img/dragonhead.ico">
<link href="/css/bootstrap.css" rel="stylesheet">
<style>
p,td {
font-size: 70%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-resource.min.js"></script>
</head>
<body ng-app="ctrljs">
<?php
$_SESSION['simpanun8']=null;
$ssloginadmin=$_SESSION['ssloginadmin'];
$page=isset($_REQUEST['page'])?$_REQUEST['page']:null;
if($page=='form'){
?>
<form method='post' name='formupgrade' ng-controller='formctrl'>
<table>
<tr><td>Username : <em>(using comma if multiuser)</em></td></tr>
<tr>
<td>
<select name='username' id='username' ng-model='username' required>
<option value='' selected></option>
<?php
$q=mysql_query("SELECT username FROM t_un WHERE upgrade='1' and t1count='0' and t2count='0' ORDER BY username");
while($f=mysql_fetch_object($q)){
?>
<option value='<?php echo "$f->username";?>'><?php echo "$f->username";?></option>
<?php
}
?>
</select>
<input type='button' value='add' onclick='checkusername();'></input>
</td>
</tr>
<tr>
<td>
<input name='usernameresult' ng-model='usernameresult' required ng-pattern="/^[A-Za-z0-9/\.\-\s\,]*$/"></input>
</td>
</tr>
</table>
<input type='submit' value='submit' ng-hide="!formupgrade.$valid"></input>
</form>
<br>
<div id='resultmunculdisini'></div>
<?php
}
?>
<script>
function checkusername(){
var status = document.getElementById("resultmunculdisini");
var u = document.getElementById("username").value;
if(u != ""){
status.innerHTML = "<font color='red'><img src='/img/loading.GIF'></img> checking...</font>";
var hr = new XMLHttpRequest();
hr.open("POST", "admintreedelrec.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "nameajax="+u;
hr.send(v);
}
}
</script>
<script>
var app = angular.module('ctrljs', []);
app.controller('formctrl', function($scope, $http){
$scope.digits = {};
});
</script>
</body>
</html>
I'm using an AJAX, and it works like a charm if I do like above,
But I don't know how put the result into an input tag.
I've tried like this, I put ID (id='resultmunculdisini') in input tag, but nothing happens:
<tr>
<td>
<input name='usernameresult' id='resultmunculdisini' ng-model='usernameresult' required ng-pattern="/^[A-Za-z0-9/\.\-\s\,]*$/"></input>
</td>
</tr>
And I change my old ID inactive, like this:
<!--<div id='resultmunculdisini'></div>-->
input will not have innerhtml, it will have value.
document.getElementById("resultmunculdisini").value=hr.responseText;
you have given same id(resultmunculdisini) to multible dom elements(div and input). id should be unique. remove the id of the div as resultmunculdisini
another.php
<?php
include('c2gcon.php');
include('logincheckadmin.php');
$nameajax=isset($_REQUEST['nameajax'])?$_REQUEST['nameajax']:null;
if($nameajax<>null){
$username=$nameajax;
$_SESSION['simpanun8']=$_SESSION['simpanun8'].','.$username;
$_SESSION['simpanun8'][0]='';
echo "username=$_SESSION[simpanun8]";
exit;
}
?>
your php script
hr.open("POST", "another.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "nameajax="+u;
hr.send(v);
this is without XMLHttpRequest
<tr>
<td>
<input name='usernameresult' id='resultmunculdisini' ng-model='usernameresult' required ng-pattern="/^[A-Za-z0-9/\.\-\s\,]*$/" value="<?php echo "$_SESSION[simpanun8]";?>"></input>
</td>
</tr>
<form method='post' name='formupgrade' ng-controller='formctrl' action="admintreedelrec.php">
<select name='nameajax' id='username' ng-model='username' required>
<option value='' selected></option>
<?php
$q=mysql_query("SELECT username FROM t_un WHERE upgrade='1' and t1count='0' and t2count='0' ORDER BY username");
while($f=mysql_fetch_object($q)){
?>
<option value='<?php echo "$f->username";?>'><?php echo "$f->username";?></option>
<?php
}
?>
</select>
<input type='button' value='add' onclick='checkusername();'></input>
<input type='submit' value='add'></input>
</form>

Pass PHP select option box values to another page

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>

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