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.
Related
***UPDATE
I've done away with table elements as suggested and am using CSS. I've also seen that there's a "form" attribute, I've tried that, too. When I submit, it is still acting as it did before - sending the wrong value because it was sending the whole table. I've updated the below with the updated HTML output and the PHP code. It looks correct, this is my latest attempt. What am I missing?
I am using PHP to create a form for each row of data. I call to PHP via AJAX. The form builds correctly. Each row correctly lists its values and is in its own form. In this example, there are three rows, thus three forms. When I submit a username on the first row, the ID being sent is from the third row. Not sure what is going on.
AJAX call to PHP FORM - Home Page
<script>
window.onload = function signupForm() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupForm").innerHTML = this.responseText;
}
}
xmlHttp.open("GET", "ajaxInput.php", true);
xmlHttp.send();
}
</script>
PHP FORM - signupForm.php
<?php
$con=mysqli_connect("localhost","xxxxxx","xxxxxxx","xxxxxxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, DATE_FORMAT(startTime, '%b-%d-%Y') as eventDate, endTime FROM events
WHERE now() < endTime");
echo "
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class='table'>
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>";
while($row = mysqli_fetch_array($result))
{
//echo "<form action='ajaxSignup.php' method='post'>";
echo "<div>";
echo "<div>" . $row['id'] . "</div>";
echo "<div>" . $row['eventDate'] . "</div>";
echo "<div><form id='form" .$row['id']. "' method='post'><input class='formSignup' type='text' name='pi_username' id='pi_username' maxlength='20' placeholder='#username' form='form" .$row['id']. "'></div>";
echo "<div><input class='formSignup' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
<input name='submit". $row['id'] . "' type='submit' value='Sign up!' onclick='signup(); return false;'></form></div>";
echo "</div>";
}
//echo "</div>";
echo "</div>";
mysqli_close($con);
?>
The table draws correctly. I've put form tag in various places as well. Below, I'm using the form attribute in the input tags. The table is being drawn with CSS instead of the table elements.
<html>
<head></head>
<body>
<p>Something here</p>
<div id="signupForm">
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class="table">
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>
<div>
<div>11</div>
<div>Feb-25-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form11"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="11" form="form11">
<form id="form11" method="post"><input name="submit11" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>12</div>
<div>Feb-26-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form12"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="12" form="form12">
<form id="form12" method="post"><input name="submit12" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>13</div>
<div>Feb-27-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form13"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="13" form="form13">
<form id="form13" method="post"><input name="submit13" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
</div>
</div>
As can be seen in the PHP, each row is its own form. But looking at the Elements in developer tools, the form is closing early. I think this is related to the issue.
Elements
When I enter a username on row one (top row), the username doesn't seem to make it and the ID that does make it is 13 instead of 11.
AJAX Script to process Submit button onclick (Home page)...
<script>
function signup() {
var elements = document.getElementsByClassName("formSignup");
var formData = new FormData();
for(var i=0; i<elements.length; i++) {
formData.append(elements[i].name, elements[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupSuccess").innerHTML = this.responseText;
}
}
xmlHttp.open("post", "ajaxSignup.php");
xmlHttp.send(formData);
}
</script>
PHP code on signup page. I have some echos early on that show the id is 13, not 11 and no username is present.
<?php
$pi_username = $high_score = $attempts = $event_id = "";
echo $event_id;
echo $pi_username;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pi_username = test_input($_POST["pi_username"]);
$event_id = test_input($_POST["event_id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo $event_id;
echo $pi_username;
if($_SERVER["REQUEST_METHOD"] == "POST") {
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxxxxx", "xxxxxxx", "xxxxxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//check if user has already signed up for event
$alreadySignedUp = mysqli_query($link, "SELECT count(*) AS total FROM signup WHERE event_id = $event_id AND pi_username = '$pi_username'");
while ($worm = mysqli_fetch_array($alreadySignedUp)){
//echo $bird['total'];
if($worm['total'] >= 1 ){
echo "You have already signed up for this event.";
echo $event_id;
echo $pi_username;
echo $worm['total'];
mysqli_close($link);
return;
}
}
// Attempt insert query execution
$sql = "INSERT INTO signup (event_id, pi_username) VALUES ('$event_id', '$pi_username')";
if(mysqli_query($link, $sql)){
echo "You have been successfully added to event ".$event_id."!";
mysqli_close($link);
return;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
else {
echo "Don't forget to submit your high scores before you leave!";
}
?>
Where am I going wrong?
The signup() function was looking for elements with the same class (formSignup). All input fields had the same class name and were all being sent to the signup() function. I've updated the class name to be unique for each row. Now only a single row is being sent. The signup() function was updated to:
window.onload = function signupForm(getClass) {
var xmlHttp = new XMLHttpRequest(getClass);
Example of an input field with a unique class name:
<input class='formSignup" .$row['id']. "' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
Removed table elements and created a CSS-styled 'table' as suggested. All working now. Question updated with CSS-Styled table.
I'm trying to make a dependable dropdown lists on PHP with AJAX calls. There are 9 columns on the MySQL table. I found a sample code. There were 3 dropdown lists. And I tried to increase them.
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title></title>
<META NAME="DESCRIPTION" CONTENT="">
<META NAME="KEYWORDS" CONTENT="">
<script type="text/javascript">
function ajaxFunction(choice)
{
{
alert(choice.options.length);}
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 stateChanged()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myObject = JSON.parse(httpxml.responseText);
for(j=document.myForm.state.options.length-1;j>=0;j--)
{
document.myForm.state.remove(j);
}
var state1=myObject.value.state1;
var optn = document.createElement("OPTION");
optn.text = 'Select State';
optn.value = '';
document.myForm.state.options.add(optn);
for (i=0;i<myObject.state.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.state[i];
optn.value = myObject.state[i];
document.myForm.state.options.add(optn);
if(optn.value==state1){
var k= i+1;
document.myForm.state.options[k].selected=true;
}
}
//////////////////////////
for(j=document.myForm.city.options.length-1;j>=0;j--)
{
document.myForm.city.remove(j);
}
var city1=myObject.value.city1;
//alert(city1);
for (i=0;i<myObject.city.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.city[i];
optn.value = myObject.city[i];
document.myForm.city.options.add(optn);
if(optn.value==city1){
document.myForm.city.options[i].selected=true;
}
}
////////////////////
for(j=document.myForm.country.options.length-1;j>=0;j--)
{
document.myForm.country.remove(j);
}
var name1=myObject.value.name1;
var optn = document.createElement("OPTION");
optn.text = 'Select Name';
optn.value = '';
document.myForm.country.options.add(optn);
for (i=0;i<myObject.name.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.name[i];
optn.value = myObject.name[i];
document.myForm.country.options.add(optn);
if(optn.value==name1){
var k= i+1;
document.myForm.name.options[k].selected=true;
}
}
///////////////////////////
document.getElementById("txtHint").style.background='#00f040';
document.getElementById("txtHint").innerHTML='done';
//setTimeout("document.getElementById('txtHint').style.display='none'",3000)
}
}
var url="ajax-dd3ck.php";
var country=myForm.country.value;
if(choice != 's1'){
var state=myForm.state.value;
var city=myForm.city.value;
var name=myForm.name.value;
}else{
var state='';
var city='';
var name='';
}
url=url+"?country="+country;
url=url+"&state="+state;
url=url+"&city="+city;
url=url+"&name="+name;
url=url+"&id="+Math.random();
myForm.st.value=state;
//alert(url);
document.getElementById("txtHint2").innerHTML=url;
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
document.getElementById("txtHint").innerHTML="Please Wait....";
document.getElementById("txtHint").style.background='#f1f1f1';
}
</script>
</head>
<body >
</head>
<body>
<div id="txtHint" style="width : 100px;background-color: #cccc33;">Message area</div>
<br><br>
<form name="myForm" action='ajax-dd3-details.php' method='post'">
<input type=hidden name=st value=0>
<table width=500>
<tr><td >
Select Country<br><select name="country" id="s1" onchange="ajaxFunction(this);">
<option value=''>Select One</option>
<?Php
//require "../include/z_db1.php";
require "config.php";// connection to database
$sql="select distinct country from student5 ";
foreach ($dbo->query($sql) as $row) {
echo "<option value=$row[country]>$row[country]</option>";
}
?>
</select>
</td><td ><select name=state id="s2" onchange="ajaxFunction(this)";>
<option value=''>Select One</option></select></td>
<td ><select name=city id="s3" onchange="ajaxFunction(this);">
<option value=''>Select One</option></select></td>
<td ><select name=sex id="s4" onchange="ajaxFunction(this);">
<option value=''>Select One</option></select></td>
</tr></tr>
<tr><td colspan=3><input type=submit value='Submit'></td></tr>
</form>
</table>
<br><br>
<div id="txtHint2"></div>
</body>
</html>
I edited this php file and added below code. Because I want to add name column from mysql to dropdown:
////////////////////
for(j=document.myForm.name.options.length-1;j>=0;j--)
{
document.myForm.name.remove(j);
}
var name1=myObject.value.name1;
var optn = document.createElement("OPTION");
optn.text = 'Select Name';
optn.value = '';
document.myForm.name.options.add(optn);
for (i=0;i<myObject.name.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myObject.name[i];
optn.value = myObject.name[i];
document.myForm.name.options.add(optn);
if(optn.value==name1){
var k= i+1;
document.myForm.name.options[k].selected=true;
}
}
I also edited the other php file:
<?Php
require "config.php"; // connection details
error_reporting(0);// With this no error reporting will be there
//////////
/////////////////////////////////////////////////////////////////////////////
$country=$_GET['country'];//
//$country='IND'; // To check you can use this
$state1=$_GET['state'];
$city1=$_GET['city'];
$name1=$_GET['name'];
//$state1="Andhra Pradesh";
///////////// Validate the inputs ////////////
// Checking country variable ///
if((strlen($country)) > 0 and (!ctype_alpha($country))){
echo "Data Error";
exit;
}
// Checking state variable (with space ) ///
if ((strlen($state1)) > 0 and ctype_alpha(str_replace(' ', '', $state1)) === false) {
echo "Data Error";
exit;
}
// Checking class variable ///
if((strlen($name1)) > 0 and (!ctype_alpha($name1))){
echo "Data Error";
exit;
}
/////////// end of input validation //////
if(strlen($country) > 0){
$q_country="select distinct(state) from student5 where country = '$country'";
}else{
$q_country="select distinct(state) from student5";
}
//echo $q_country;
$sth = $dbo->prepare($q_country);
$sth->execute();
$state = $sth->fetchAll(PDO::FETCH_COLUMN);
$q_state="select distinct(city) from student5 where ";
if(strlen($country) > 0){
$q_state= $q_state . " country = '$country' ";
}
if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";}
$sth = $dbo->prepare($q_state);
$sth->execute();
$city = $sth->fetchAll(PDO::FETCH_COLUMN);
$q_name="select distinct(name) from student5 where ";
if(strlen($country) > 0){
$q_state= $q_state . " country = '$country' ";
}
if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";}
if(strlen($city1) > 0){$q_city= $q_city . " and city='$city1'";}
$sth = $dbo->prepare($q_city);
$sth->execute();
$name = $sth->fetchAll(PDO::FETCH_COLUMN);
$main = array('state'=>$state,'city'=>$city,'name'=>$name1, 'value'=>array("state1"=>"$state1","city1"=>"$city1", "name"=>"$name1"));
echo json_encode($main);
////////////End of script /////////////////////////////////////////////////////////////////////////////////
?>
I added that code to above:
$q_name="select distinct(name) from student5 where ";
if(strlen($country) > 0){
$q_state= $q_state . " country = '$country' ";
}
if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";}
if(strlen($city1) > 0){$q_city= $q_city . " and city='$city1'";}
$sth = $dbo->prepare($q_city);
$sth->execute();
$name = $sth->fetchAll(PDO::FETCH_COLUMN);
When I open it via LAMP, new dropdown list doesn't work. And I got this error. What can I fix this?
Edit: And here is what i mean with "name"
document.myForm.name.options.length this is giving you error. You have to use the name of select to get options length. So Use like document.myForm.country.options.length
So in your scenario, you have to do like this.
In HTML
<select name=country id='s1' onchange=ajaxFunction(this);>
And in JS
function ajaxFunction(choice) {
alert(choice.options.length);}
I can see a couple of minor errors also which will not help!
<form name="myForm" action='ajax-dd3-details.php' method='post' ">
<input type=hidden name=st value=0>
There is a spurious double quote at the end of the form opening tag, should simply be:
<form name="myForm" action='ajax-dd3-details.php' method='post'>
and you really ought to encase values with quotes in your fields...
<input type='hidden' name='st' value='0' />
Similarly for various other elements within your form, such as:-
<select name=country id='s1' onchange=ajaxFunction('s1');>
should be
<select name='country' id='s1' onchange="ajaxFunction('s1')">
I know others will likely disagree, especially as HTML5 seems more relaxed about this type of thing but it's good practice to adopt and helps figure where things are breaking.
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>
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>';
?>
I found one of basic php live search using ajax from youtube.com please see the sample at
http://www.youtube.com/watch?v=3fS4Ys_ZEKw that video speaking different language but i manager to type all of codes exactly of what you see from youtube.com , but different is the database name and table name, however, when I run is not showing anything to bring from mysql database even if pressed any key still not showing anything and not even errors. Can you see if i missed anything on this code compare to what you see from youtube!
search.php
<body>
<form name"form1" action="" method="post">
Enter name<input type="text" name="t1" onKeyUp="aa();"/><br />
<div id="dl"></div>
</form>
<script type="text/javascript">
function aa()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","sea.php?nm="+document.forml.t1.value,false);
xmlhttp.send(null);
document.getElementById("dl").innerHTML=xmlhttp.responseText;
}
</script>
</body>
</html>
sea.php
<?php
$nm=$_GET("nm");
$mysqli = new mysqli("localhost", "root", "password", "table");
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($result = $mysqli->query("select * FROM product WHERE product_name like('$nm%')"))
echo"<table>";
{
echo "<tr>";
echo "<td>";?><img src="../<?php echo $row["screenshot"];?>" height="100" width="100" <?php echo "</td>" ;
echo "<td>"; echo $row["product_name"]; echo "</td>";
echo "<tr>";
}
echo "</table>";
?>
you need to get the response on onreadystatechange, do:
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) { //4:: request finished and response is ready
document.getElementById("dl").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sea.php?nm="+document.forml.t1.value);
xmlhttp.send(null);