Run SQL query and update form on drop-down selection - php

So I have two drop-down lists Category and Sub-category. Sub-category has to be populated by an SQL query once a Category is selected.
I know how to populate from an SQL query:
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table";
$result = mysql_query($sql);
echo "<select name='col'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
But I don't know how to run the query and update list in jQuery:
function updateList(){
//QUERY&fill based on selection//
.val($('select[name="category"] option:selected').val());
}
I spent an hour or so on google and couldn't manage to solve this.

you have to create onchange function in selecting main category and pass it to either jquery or javascript ajax request response to get value from another file having subcategory output with sql where condition as main category value.
echo "<select name='col' onchange='loadXMLDoc()'>";
the above of main cat drop down and its ajax javascript reqest response whould be as below
<script>
function loadXMLDoc()
var maincat=document.getElementByName("col").val();
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("maincat_var=maincat");
}
Create a div with id as myDiv in your main page.
and the other page should have
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table where main_cat=$_POST['maincat_var']";
$result = mysql_query($sql);
echo "<select name='col2'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>

You can try using jquery and ajax to load values of subcategory .
Try modifying and using the below code. This code may guide you..
$(document).ready(function(){
$('#submit').click(function() {
$.ajax(
{
url:"subcat.php?id='something'", // Here you can write php variableto pass to next page
success:function(result){
$("#div1").html(result);
}
});
return false;
});
});
onclicking the main category some page will be executed and its output will be displayed in a html element.

Related

Trouble Getting AJAX GET to work with whitepsace

I have a MYSQL table called orgs that has columns for name, city, zip, and state. I want an AJAX dropdown that populates another field on my page with the name of the cities when I select the name of the city from the dropdown. I currently have the dropdown for the city updating based on what state I have but when I try the call for the organizations name based on the city my code fails. Here's what I currently have.
AJAX to get the names of the cities:
function list(str)
{
if (str=="")
{
document.getElementById("list").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("list").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../php/list_org.php?q="+str,true);
xmlhttp.send();
}
AJAX to get the names of the organizations based on the cities:
function get_cities(str)
{
if (str=="")
{
document.getElementById("get_cities").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("get_cities").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../php/get_cities.php?q="+str,true);
xmlhttp.send();
}
list_org.php:
<?php include_once '../php/db_connect.php'; ?>
<?php
$q = strval($_GET['q']);
$sql2="SELECT DISTINCT city FROM orgs WHERE state= '".$q."'";
$result2=mysqli_query($connection,$sql2);
if(!$result2){
die("Database query failed. " . mysqli_error($connection));
}
echo "<form>";
echo '<select name="get_cities" onchange="get_cities(this.value)">';
echo '<option value="">Select a city:</option>';
while($row2= mysqli_fetch_array($result2)){
echo '<option value="' . $row2['city']. '">'. $row2['city'].'</option>';
}
echo "</form>";
mysqli_close($connection);
?>
get_cities.php:
<?php include_once '../php/db_connect.php'; ?>
<?php
$q = strval($_GET['q']);
$q='CA';
$sql2="SELECT * FROM orgs WHERE state = '".$q."'";
$result=mysqli_query($connection,$sql2);
if(!$result){
die("Database query failed. " . mysqli_error($connection));
}
echo $q;
$link_address = '#';
echo '<div id="get_cities">';
while($row = mysqli_fetch_array($result))
{
echo "<ul>";
echo "<li><a href='".$link_address."' name='" . $row['id'] ."'>" . $row['name'] . "</a></li>";
echo "</ul>";
}
echo '</div>'
mysqli_close($connection);
?>
I thought the problem was probably that I was passing cities with whitespace in them (like "los angeles") but I've tried it with single name cities like "Buffalo" and nothing happens when I change my selection either. Any help would be greatly appreciated.
You are missing a </select> in list_org.php. Try to fix that one first, then escape your string.
Replace
xmlhttp.open("GET","../php/get_cities.php?q="+str,true);
to
xmlhttp.open("GET","../php/get_cities.php?q="+escape(str),true);

Ajax mysql query not producing any data

Im very inexperienced with php and myadmin and have been trying to utilise some tutorials to use ajax to query a database.
I firstly want to loop through the database to give me a drop down list of options to choose from ie:
Food
Petrol
Shopping
Entertainment
Then I want the user to be able to select one of the dropdown options and this then will query the database and produce a table with data on that selection
ie if they choose petrol it will produce a table
Payee Amount Date
Tesco 23.00 27/10/13
Sainsbury 20.00 20/10/13 etc
Here is my code for the ajax
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("output").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("output").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","catagory.php?catagory="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$server = 'localhost';
$user='root';
$pass='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $pass, $db);
$query = $mysqli->query("SELECT distinct `catagory` FROM `transactions`");
while($array[]= $query->fetch_object());
array_pop($array);
?>
<h3>Transactions</h3>
<select name="the_name" onchange="showUser(this.value)">
<?php foreach ($array as $option): ?>
<option value="<?php echo $option->Transaction; ?>"><?php echo $option -> catagory;?></option>
<?php endforeach; ?>
</select>
<div id="ouput"<b>Transactions:</b></div>
<?php
$query-> close();
?>
</body>
</html>
And here is my code to query the database:
<?php
$q = $_GET['catagory'];
$con = mysqli_connect('localhost','root','','finance_checker');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"finance_checker");
$sql="SELECT `ThirdParty`, `Credit`,`Date` FROM `transactions` WHERE `catagory` = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Payee</th>
<th>Amount</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ThirdParty'] . "</td>";
echo "<td>" . $row['Credit'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The initial code is producing the correct dropdown options, however when I select one of the options I do not get anything reproduced.
I thought I had understood what was going on but clearly somewhere I have missed something would anyone be able to offer further guidance?
Since you only...
SELECT distinct `catagory` FROM `transactions`
...$option->Transaction would always be undefined.
When you load data in select box please check the select query. Try below one
$query = $mysqli->query("SELECT distinct `catagory`,`Transaction` FROM `transactions`");

Where does code for a dynamic AJAX Submit button go? How do you architect a dynamic AJAX php/javascript webpage?

Here is my Question:
I have a dynamic list that displays X classes. when a class is selected, all the students of the class are displayed. When a user clicks "submit", I want to send an insert statement to the database. Where does the code for the submit button go?
My Attempt: Pseudocode/structure
Files placed in 1 folder on webserver: Index.php and getStudentList.php
Index.php
<script>
function showStudents(str)
blabla
xmlhttp.open("GET","getStudentList.php?q="+str, true);
xmlhttp.send();
</script>
...
<div>
html display goes here, as well as the form itself
</div>
getStudentList.php
<script>
logic for javascript goes here which connects to a db and inserts attendance info
</script>
<?php
connect to db
query students in class
echo attendance form
?>
Detailed Code:
Index.php
<!--start script for AJAX attendance display-->
<script>
function showStudents(str)
{
if (str=="") {
document.getElementById("attendanceForm").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("attendanceForm").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getStudentList.php?q="+str,true);
xmlhttp.send();
}
<script>
<div>
<?php
//identify teacher's classes
$school_connection = New school();
$arrayTeachersClasses = $school_connection->queryTeachersClasses($_SESSION['teacherID']);
//returns array of all classes taught
//echoes today's date
echo Date("l F d, Y");
//create list so teacher can pick class
echo "<form>";
echo "<select name = \"courses\" onchange = \"showStudents(this.value)\">";
echo "<option value=\"\">Select a class:</option>";
$i = 0;//counter
while ($row = $arrayTeachersClasses[$i]) {
echo "<option value=\"". $row[0] . "\">";
echo $row[1] . " ". $row[2] . "-L". $row[3] . " Room " . $row[4];
echo "</option>";
$i++;
}
echo "</select>";
echo "</form>";
/***
//Sample "Select a Class" list
<form>
<select name="users" onchange="function(this.value)">
<option value="">Select a class:</option>
<option value="0">09:00:00 BEG-L1 Room303</option>
<option value="1">TIME SUBJ-LEVEL ROOM</option>
<option value="2">ditto</option>
<option value="3">ditto</option>
</select>
</form>
*/
$teacherID = $_SESSION['teacherID'];
//echo $teacherID;
?>
</div>
<br />
<div id="attendanceForm">
<p><b>Attendance List:</b></p>
Please Select a Class
</div>
getStudentList.php
<script>
//Other JS stuff
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
$i = 0;//counter
var attendanceData = new Array();
//Get the data for each student
while ($row = $arrayStudentList[$i]) {
var studentID = $('input[name=' . $row[0] . ']');
if (studentID.val()=='') {
studentID.addClass('highlight');
return false;
} else studentID.removeClass('highlight');
$row[2] = studentID.val;
$attendanceData[$i] = $row;
$i++;
}
$row = $attendanceData[0];
$record = $row[2];
alert("My First JavaScript");
//cancel the submit button default behaviours
return false;
});
});
</script>
there are many ways of doing this...
Below are 2 simple solutions: with postback or through ajax.
Options 1 - Postback
when submit is clicked submit the form to the index page itself: leave form action blank or use $_SERVER['PHP_SELF']
in index.php prior to displaying anything check request type & params and save data
generate success/failure message and display
Option 2 - Ajax
create new page insertStudent.php
Add ajax functionality to form submit and send form to insertStudent.php. see jquery submit or reinvent the wheel for your project
In insertStudent.php save the student and return json status or (1/0)
handle the response in your ajax handler (step 2) to display success/failure message
Hoe this helps you with your homework ;-)

retrieve sql data & print it into form field

here is an example that if i enter id then it will retrieve data from database & print it within form fields. my database has only three column- id, name & number. here is my index.html file:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
return true;
</script>
</head>
<body>
<p>Please Enter Your Staff ID:</p>
<div><input onkeyup="if (event.keyCode == 13) showData(this.value); return false;" /></div>
<div id="ajax-content"></div>
</body>
</html>
and here is my showData.php file:
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("test_01", $con);
// Select all fields from your table
$sql="SELECT * FROM staffdetails WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "Staff Name:" . "<input type='text' value='" . $row['name'] . "'>";
echo "</br>";
echo "Contact No.:" . "<input type='text' value='" . $row['number'] . "'>";
}
// Close the connection
mysql_close($con);
?>
now what i'm trying to do is, display the data in a given form field rather than print data with the form field. that means, the name & number input field will be already in the form with the id field. when i'll enter id then it will pull back the data & display it in the given form field. anyone can help please? thanks!
There's a javascript error in your index.html page. The return true statment should be inside function brackets.
Also try adding document type and content type on top of index.html page to show text fields instead of printing it.
Hope this will help solving your problem.

value not getting posted from the element generated by ajax class

This is the HTML form
echo "<tr><td>Course</td><td><select name='Course' onchange='branch_selector(this.value)'>";
echo "<option value='B.Tech'>B.Tech</option>";
echo "<option value='M.Tech'>M.Tech</option>";
echo "<option value='MBA'>MBA</option>";
echo "<option value='MCA'>MCA</option>";
echo "</select></td></tr>";
echo "<tr><td><div id='branch_div_name'></div></td><td><div id='branch_div'></div></td></tr>";
this is the javascript code
function branch_selector(val) {
if(val=='B.Tech' || val=='M.Tech') {
show_name('branch_div_name','Branch');
var xmlhttp;
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('branch_div').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","branch_selector.php",true);
xmlhttp.send();
}
else {
document.getElementById("branch_div").innerHTML="";
disappear_name('branch_div_name');
}
}
This is the PHP code running at the backened
$result = mysql_query("SELECT DISTINCT Branch FROM student_main ORDER BY Branch ASC") or die(mysql_error());
echo "<select name='Branch' id='Branch' onchange='harb()'>";
while($row = mysql_fetch_array($result)) {
if($row[0]=='' or $row[0]=='N/A') {
continue;
}
else {
echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
}
echo "</select>";
The dropdown is generated without any problem. But when the form is submitted the $_POST['Branch'] is not set.
Please help
Ok, I have solved this issue, The solution is not the best but its getting the job done.
I am using now a hidden field and the value is this field is set according to the value of Branch of. The value is set using Javascript when user click on submit.
Its working fine, no issue whatsoever but if someone have better solution, please share.

Categories