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.
Related
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.
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);
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.
I'm trying to use Ajax, PHP, and MySQL together to make a form element, drop-down style select input be able to select an option and have the ajax sent data through the script to the database and back to the page to a separate div. I have most of the code for this figured out. My issue now is this.
I have three drop-down menus that 1 would like to have go to this script. It would then go to three different $GET scripts depending on which menu it was selected from.
<script type="text/javascript">
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","getuser.php?q="+str,true);
xmlhttp.send(); }
</script>
The three select elements I have are accompanied with onchange functions.
<select name="characters" onchange="showCharacter(this.value)">
<select name="towers" onchange="showTowers(this.value)">
<select name="enemies" onchange="showEnemies(this.value)">
The PHP code I have for this script is this:
<?php
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
mysql_select_db("db1801445-main", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
$q=$_GET["q"];
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Description</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Idk how else to do this so can you guys help me?
I agree that using jQuery would make your life easier, but to address your question:
You could make that JS code more general so it would be easier to reuse:
<script type="text/javascript">
function doAjax(ajaxFunction, 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","getuser.php?q="+str+"func="+ajaxFunction,true);
xmlhttp.send(); }
</script>
And then change you PHP do this:
<?php
$sFunction = $_GET["func"];
$sQ =$_GET["q"];
switch($sFunction){
case 'showUser':
//code here;
break;
case 'showTowers':
//code here;
break;
case 'showEnemies':
//code here;
break;
case 'showCharacters':
//code here;
break;
}
?>
And back on the frontend:
<select name="characters" onchange="doAjax('showCharacter',this.value)">
<select name="towers" onchange="doAjax('showTowers',this.value)">
<select name="enemies" onchange="doAjax('showEnemies',this.value)">
So close, yet so far. There is a table that displays the status of trouble ticket's (submitted, open, closed), when the ID of a ticket is clicked, more info is displayed and a button is given to Open the ticket or Close it. The button has an onClick event that sends the AJAX to work, and the button works as far as updating the status of the ticket is concered. Howeever, upon update the in the display table that shows the Status should update as well, but does not.
Button:
if ($ticketarray['status'] == "0") {
// print option to open ticket
echo "<form>";
echo "<input type=\"button\" name=\"". $ticketarray['id'] ."\" value=\"Open Ticket\" onClick=\"statusChange(". $ticketarray['id'] .")\" />";
echo "</form>";
}
if ($ticketarray['status'] == "1") {
// print option to close ticket
echo "<form>";
echo "<input type=\"button\" name=\"". $ticketarray['id'] ."\" value=\"Close Ticket\" onClick=\"statusChange(". $ticketarray['id'] .")\" />";
echo "</form>";
}
Table:
echo "<td name=\"statusholder\" style=\"padding: 0px;margin: 0px;\" /><div style=\"font-color: ". $fontcolor .";font-weight: bold;background-color: ". $statuscolor .";text-align: center;width: 100%;height: 100%;visibility: visible;\" name=\"statusdiv\">". statusTranslator($tixarray['status']) ."</div></td>";
AJAX:
function statusChange(str) {
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('statusdiv').style.visibility = hidden;
document.getElementById('statusholder').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","statuschange.php?id="+str,true);
xmlhttp.send();
}
STATUSCHANGE.PHP:
<?
include("./header.php");
if (isset($_GET['id'])) {
// valid request, get current status
$currentstatus = mysql_query("SELECT status FROM `table` WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("Cannot get current ticket status ". mysql_error());
$currentarray = mysql_fetch_assoc($currentstatus) or die("cannot make array ". mysql_error());
if ($currentarray['status'] == "0") {
// currently Submitted, make Open
mysql_query("UPDATE `table` SET status='1' WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("cannot update status ". mysql_error());
// send reformatted status div
echo "<div style=\"font-color: #000;font-weight: bold;background-color: #FFFF00;text-align: center;width: 100%;height: 100%;\" name=\"statusdiv_updated\">Open</div>";
}
if ($currentarray['status'] == "1") {
// currently Submitted, make Open
mysql_query("UPDATE `table` SET status='2' WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("cannot update status ". mysql_error());
// send reformatted status div
echo "<div style=\"font-color: #000;font-weight: bold;background-color: #33CC00;text-align: center;width: 100%;height: 100%;\" name=\"statusdiv_updated\">Completed (Closed)</div>";
}
} else {
echo "nothing to do here";
}
?>
On this line
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
remove the
&& xmlhttp.status==200
and it should work fine :-)