Output of drop down list in php mysql - javascript

I want the output of "cor_resp_template" where is nome and select that values for in next page do some operations like(sum, multiplication,...). I try the first time use JavaScript, but i don´t know if the code is correct. I try to analysis step by step and seems ok for that operation.
In next picture like you see the empty values. Don´t show the table with the values for after submit that values for next page.
The output of database of the table template where is all the values:
That is the output of that page:
http://localhost/dissertacao/conceptualization13.php?menuId=1
After we have the code where we use the JavaScript for get the values in next page where is the PHP query.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("$option").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("$option").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","template1.php?option="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<?php
echo "<select name='template' class='form-control' onchange='showUser(this.value)'>";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
echo "<center>";
// Get the county names from database - no duplicates
$query = "SELECT DISTINCT nome FROM template";
{
// execute the query, $result will hold all of the Counties in an array
$resultado = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($resultado))
$option .="<option>" . $row['nome'] . "</option>";
echo $option;
}
echo "</select>";
echo "<br>";
?>
<input type="submit" value="Submit">
</form>
<br>
<div id="valores"><b>Os valores para este template são:</b></div>
template1.php
The following code is the PHP QUERY where is called for give the output of the table with the values where is nome in the SQL table.
<?php
$option = (isset($_POST['nome']) ? $_POST['nome'] : '');
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
$query="SELECT * FROM template WHERE 'nome' = '".$option."'";
$resultado = mysql_query($query) or die(mysql_error());
echo "<table>
<tr>
<th>Valores</th>
</tr>";
while($row = mysql_fetch_array($resultado)) {
var_dump ($resultado);
echo "<tr>";
echo "<td>" . $row['corp_resp_template'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>**

Related

How to get the selected value from dropdown and use it in query without clicking submit?

I'm making a chart that will show its result based from the year that was selected from the dropdown. Is it possible to get the variable from the dropdown and use it in query without clicking submit button? I tried this code but didn't work out:
<?php
require '../includes/dbheader.php';
$query = "SELECT DISTINCT DATE_FORMAT(orderdate, '%Y') AS year
FROM prodsoldmonthly
";
$result = mysqli_query($conn, $query);
echo "<select id='selectyear[]' name='selectyear' class='cd-select filter-input'>";
echo "<option class='dropdown' value='' selected>Choose Year</option>";
while($row = mysqli_fetch_assoc($result)) {
echo "<option class='dropdown' value='{$row['year']}'>".htmlspecialchars($row["year"])."</option>";
}
echo "</select>";
?>
<script>
$yearselected = $("#selectyear option:selected").text();
</script>
<!-- Products Sold per Category -- YEAR -->
<?php
include('../includes/dbheader.php');
$query = "SELECT categoryName, qty, DATE_FORMAT(orderdate, '%Y') AS year
FROM prodsoldmonthly WHERE year = '$yearselected'
";
$result = mysqli_query($conn, $query);
?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['categoryName', 'qty'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["categoryName"]."', ".$row["qty"]."],";
}
?>
]);
var options = {
title: 'Products Sold Per Category by Year',
is3D:true,
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('piechartyear'));
chart.draw(data, options);
}
</script>
You can use AJAX to launch the request with the year without having to submit the whole page:
function queryProducts(yearselected) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this line will be called when the query finishes successfully
document.getElementById("products").innerHTML = this.responseText;
}
};
// set url with parameter
xmlhttp.open("GET", "products.php?yearselected=" + selectedyear, true);
xmlhttp.send();
}
Add an 'onchange' listener to your select to call the function while passing the selected year:
<select id='selectyear[]' name='selectyear' onchange="queryProducts(this.value)" class='cd-select filter-input'>";
Lastly, add a placeholder to display the result of the query:
<div id="products"></div>
EDIT:
For your select statement, put the code in another page like products.php for example and call that page in the AJAX function:
<?php
// products.php
include('../includes/dbheader.php');
// get url parameter
$yearselected = intval($_GET['yearselected']);
$query = "SELECT categoryName, qty, DATE_FORMAT(orderdate, '%Y') AS year
FROM prodsoldmonthly WHERE year = '".$yearselected."'";
$result = mysqli_query($conn, $query);
echo "<table>
<tr>
<th>Category</th>
<th>Qty</th>
<th>Order date</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['categoryName'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" . $row['orderdate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>

AJAX request displaying content to user but not on the source of the page

On the body of the document, lets call it "form.php" we have the following:
On the head we have a JavaScript code:
<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", "getchauffeur.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
We query to database and populate a dropdown. We switch content using (showUser):
<div>
<?
$result = $mysqli -> query("select id, nomchauffeur from chauffeurs");
echo "<select name='id' onchange='showUser(this.value)'>";
while ($row = $result -> fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['nomchauffeur'];
echo '<option value="'.$id.
'">'.$name.
'</option>';
}
?>
Here we are still in body. We put the content of AJAX into div.
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
</div>
Here is our script that populate form fields with the content of AJAX request:
<script>
var table = document.getElementById('table');
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
//rIndex = this.rowIndex;
document.getElementById("nomchauffeur").value = this.cells[0].innerHTML;
document.getElementById("prenomchauffeur").value = this.cells[1].innerHTML;
document.getElementById("agechauffeur").value = this.cells[2].innerHTML;
document.getElementById("cinchauffeur").value = this.cells[3].innerHTML;
};
}
</script>
Now here is our getchauffeur.php:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','nouveau');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$sql="SELECT * FROM chauffeurs WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>nom</th>
<th>prenom</th>
<th>age</th>
<th>adresse</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nomchauffeur'] . "</td>";
echo "<td>" . $row['prenomchauffeur'] . "</td>";
echo "<td>" . $row['agechauffeur'] . "</td>";
echo "<td>" . $row['adressechauffeur'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The Problem: Everything works fine if the table is on the same page. But here the AJAX request constraints us to put the table in other php page(chauffeur.php).
What we need is populating the form fields automatically by clicking on the row displayed from dropdown Change actions. It appears that the row inserted into table inside 'chauffeur.php' is not printed on the html DOM. When we click on page view source, it displays only:
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
And not the content of the following fields:
nomchauffeur prenomchauffeur agechauffeur adressechauffeur
How could we grab the content of row and fill automatically the form and where is it?
This whole javascript AJAX should be after your HTML div #txtHint.
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
Also you can return only row instead of whole table. On main page create table as id 'txtHint' and insert that row in response.

Using AJAX, PHP and MySQL to display table data

I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(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","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment

Sending data back from php

I tried this tutorial to send/retrieve data from my mysql database, using ajax and php.
This is the ajax part:
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","suchen_ma.php?id="+str,true);
xmlhttp.send();
}
</script>
The .php file looks like this:
<?php
//Connection Details
$username = 'root';
$password = '';
$hostname = 'localhost';
$databasename = 'plzdb';
$id = ($_GET['id']);
//Connection-string
$con = mysqli_connect($hostname,$username,$password,$databasename);
//SQL Query
$sql = "SELECT per_vorname,per_nachname from plz_person
WHERE per_id = $id";
$result = mysqli_query($con,$sql);
echo "<table border='0'>
<tr>
<th></th>
<th></th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['per_vorname'] . "</td>";
echo "<td>" . $row['per_nachname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The data is formatted within the php file, but I want to send the "raw" data back to the html and display it inside a list and format it with css. Unfortunately I have no idea how to do this
Just give back the data as JSON:
$sql = "SELECT per_vorname,per_nachname from plz_person
WHERE per_id = " . mysqli_real_escape_string($con, $id);
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
$persons[] = array(
"vorname" => $row['per_vorname'],
"per_nachname" => $row['per_nachname']
);
}
echo json_encode($persons);
and then create a loop in javascript, to build the HTML.
NOTE: Avoid sql injection by escaping your string.

using option with php and mysql

This is my table subjects in lecturer database
No subject credit_hour
1 (111) AAA 4
2 (222) BBB 3
3 (222) CCC 4
4 (333) DDD 3
This is what I have done using ajax
This is my testing1.php
<?php
$conn = mysql_connect('localhost','root','password');
mysql_select_db('lecturer');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<head>
<script>
function showUser(str)
{
if (str==="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","testing3.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="subjects" onchange="showUser(this.value)">
<option value="">Select a subject:</option>
<?php $result= mysql_query('SELECT * FROM subjects'); ?>
<?php while($row= mysql_fetch_assoc($result)) {
$list=array($row['subject'],$row['credit_hour']);
?>
<option>
<?php echo htmlspecialchars($row['subject'] ); ?>
<?php echo htmlspecialchars($row['credit_hour'] ); ?>
</option>
<?php } ?>
</select>
</form>
<br>
<div id="txtHint"><b>subject info will be listed here.</b></div>
</body>
</html>
This is my testing3.php
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','password','lecturer');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"lecturer");
$sql="SELECT * FROM subjects WHERE No = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Subject</th>
<th>Credit_hour</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . $row['credit_hour'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The problem is that when I select (111)AAA 4
it should be appearing a table which is located in testing3.php
but it did't fetch any data in the table
Thank you
After your first select query you should put the subject, hour_credit pair in an array, then on onchange event of the first option(your subject list) you should check which index is selected then set the second options selected index.

Categories

Resources