Using AJAX, PHP and MySQL to display table data - javascript

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

Related

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.

Output of drop down list in php mysql

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>";
?>**

Delete data with checkbox in a table

I display a table on the website after a select option (I use ajax) and get the datas from the database. What I want to do is to insert a checkbox in my table and when it is checked delete the row in the database. I don't want to use a submit button but only the checkbox to delete it.
I'm not really good with ajax and JavaScript. This is the code:
The select :
<p>
<label for="client">Veuillez choisir le fournisseur :</label><br />
<select name="client" id="client" onchange="showUser(this.value)">
<?php
// echo '<option value=""/></option>';
while ($donnees = $reponse->fetch())
{
echo '<option value='.$donnees['refCustomer'].'>'.$donnees['legalCompanyName'].' </option>';
//$value = $donnees['refCustomer'];
}
$reponse->closeCursor();
?>
</select>
</p>
The script :
<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","getTableBuffer.php?q="+str,true);
xmlhttp.send();
}
}
</script>
getTableBuffer.php :
<?php
$q = intval($_GET['q']);
try
{
$bdd = new PDO());
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('select * from vendor_'.$q.'_offers_ncli_amendments_buffer');
echo '<table class="imagetable">';
echo '<tr>';
echo '<th>code</th>';
echo '<th>dateAdded</th>';
echo '<th>effectiveDate</th>';
echo '<th>price</th>';
echo '<th>type</th>';
echo '<th>destination</th>';
echo '</tr>';
while ($donnees = $reponse->fetch())
{
echo '<tr>';
echo '<td><input type="checkbox" name="code" id="code" value="'.$donnees['code'].'"/>'.$donnees['code'].'</td>';
echo '<td>'.$donnees['dateAdded'].'</td>';
echo '<td>'.$donnees['effectiveDate'].'</td>';
echo '<td>'.$donnees['price'].'</td>';
echo '<td>'.$donnees['type'].'</td>';
echo '<td>'.$donnees['destination'].'</td>';
echo "</tr>";
}
echo "</table>";
echo "</br>";
echo "</br>";
$reponse->closeCursor();
?>
Add event onclick to your checkbox :
echo '<td><input onclick="remove(this);" type="checkbox" name="code" id="code" ....';
create function remove() in you javascript, that send the $donnees['code'] to a remove.php to delete it from DB :
function remove(e)
{
if (e.target.checked)
{
....
xmlhttp.open("GET","remove.php?code="+e.target.value,true);
xmlhttp.send();
}
}
Create remove.php that get the code and delete from DB :
<?php
if(isset($_GET['code'])){
//Query to remove from DB where code = $_GET['code']
}
?>
Hope this will help.

How to get database other fields on change even of dropdown

Below are my code parts javascript, main.php and getparty.php
1) getparty.php code is as follow called from javascript to take details
from party table on change of dropdown value of party from main.php
<?php
$q = intval($_GET['q']);
include "dbc.php";
$sql= mysql_query("Select a.pcode,a.pname,a.discperc,a.delvterm from PARTY a where a.pcode='$q'") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
$pcode=$row['pcode'];
$ppname=$row['pname'];
$pdiscperc=$row['discperc'];
?>
main.php ... it is my main form to display main form for user to enter
<tr>
<td><font face="verdana" size="2" color="#000000">Party</font></td>
<td>
<?php
<td align="left" >
<?php
$sql="UPDATE PARTY set repo_flag=0 ";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
if ($ppname!="")
{
$sql="UPDATE PARTY set repo_flag=1 where pname='$ppname' ";
}
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
$dropdown = "<select id='pname' name='pname' style='width:275px' onchange='showparty(this.value)' value='<?php echo $ppname; ?>' >";
$query1 = "select pcode,pname from PARTY order by repo_flag DESC ";
$get=mysql_query($query1);
while($row = mysql_fetch_array($get))
{
$dropdown .= "\r\n<option value='{$row['pcode']}'>{$row['pname']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
?>
</td>
</tr>
<tr>
<td><input type="text" maxlength="3" size="3" name="txtdiscperc" value="<?php echo $pdiscperc; ?>"/></td>
</tr>
Javascript .. This is called to take value of party when dropdown
combo changes
<script>
function showparty(str) {
if (str == "") {
document.getElementById("txtpartyname").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("txtpartyname").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getparty.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I am not getting value of Discount % in main.php, and some other fields also I want to get from party table which I can write code when above discount % gets properly. How can I

Want to get value from Select Tag by Submit button

<html>
<head>
<script>
function showUser()
{
//var s=document.getElementById('uni'); //this also not working
//var str=s.options[s.selectedIndex].value;
var str=document.form.formList.value;
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="form">
<select name="formList" id="uni" >
<option value="">Select a person:</option>
<option value="1">University 1</option>
<option value="2">University 2</option>
<option value="3">University 3</option>
<option value="4">University 4</option>
</select>
<input type="submit" value="Search" onsubmit="showUser()" >
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Want to get value from Select Tag by Submit button.....
By using javascript and then send to AJAX to forward that data to userget.php file to fetch data from SQL DATABASE and
then show to on web.
please i'm stuck here anybody tell me what i'm doing wrong... ???
I want to to store value from drop down list by submit button...
/////////////////Server side code///////////////////////////
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','degree');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM uni WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Id</th>
<th>Univeristy</th>
<th>Degree</th>
<th>Location</th>
<th>Rank</th>
<th>Fees</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Id'] . "</td>";
echo "<td>" . $row['Univeristy'] . "</td>";
echo "<td>" . $row['Degree'] . "</td>";
echo "<td>" . $row['Location'] . "</td>";
echo "<td>" . $row['Rank'] . "</td>";
echo "<td>" . $row['Fees'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
If you use JQuery, you may do something like:
$(document).ready(function(){
$('#searchButton').click(function(){
if ($('#uni').val()) {
$.post(
'getuser.php',
{
q: $('#uni').val()
},
function(personInfo){
if (personInfo) {
$('#txtHint').text(personInfo)
}
}
);
} else {
alert('Please select an option first.');
}
});
});
Just change the input type in your form from submit to button and add the id as "searchButton".
In your server side script, use POST instead of GET:
$q = intval($_POST['q']);
First of all more reliable method of getting xmlhttp
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
Second is that correct form to do what you want is that:
<form name="form" onsubmit="showUser(); return false;">
<select name="formList" id="uni" >
<option value="">Select a person:</option>
<option value="1">University 1</option>
<option value="2">University 2</option>
<option value="3">University 3</option>
<option value="4">University 4</option>
</select>
<input type="submit" value="Search" />
</form>
And showUser function like that:
function showUser()
{
//var s=document.getElementById('uni'); //this also not working
//var str=s.options[s.selectedIndex].value;
var str=document.form.formList.value;
if (str=="")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4)
{
if(xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
} else {
// add error handler here
}
}
};
xmlhttp.open("GET","/getuser.php?q="+str,true);
xmlhttp.send();
}
No need to bother with submit at all. This will do the trick :)
<input type="button" onclick="showUser();" value="Search" />

Categories

Resources