Im trying to do this: When someone selects any option from the drop down called subject, the sections drop down should show all sections of that subject. The subject drop down works well, fetches all names of subjects but the sections one won't work. Im unable to find the issue. It should fetch the sections from the database WHERE/WHEN name(database column) is equal to the subject chosen. Thanks in advance. My code is below:
my js code
<script type="text/javascript">
function getSection(strURL)
{
alert(strURL);
var req = getXMLHTTP(); // fuction to get xmlhttp object
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('sectiondiv').innerHTML=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
req.open("GET", strURL, true); //open url using get method
req.send(null);
}
}
</script>
php code:
<div>
Subject:
<?php
$conn = new mysqli('localhost', '', '', '')
or die ('Cannot connect to db');
$result = $conn->query("select name from class");
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$name = $row['name'];
echo '<option value="subject">'.$name.'</option>';
}
echo "</select>";
?>
</div>
<br>
<div id="sectiondiv">
Section:
<select name="select">
</select>
</div>
my findsection.php
<? $subject=intval($_GET[‘subject’]);;
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$mysqli = new Mysqli($servername, $username, $password, $dbname) or mysqli_error($mysqli);
$section = $mysqli->query("SELECT section FROM class WHERE name = '$subject'")->fetch_object()->section;
$result=mysql_query($section);?>
<select name="section">
<? while ($row = $result->fetch_assoc()) { ?>
<option value><?=$row['section']?></option>
<? } ?>
</select>
You have incomplete/invalid html
echo "<select name='subject' onchange='getSection('findsection.php?subject=>'this.value'";
Change it to this
echo '<select name="subject" onchange="getSection(\'findsection.php?subject=\' + this.value)">';
Related
I am getting the id of selected option value But the table data is not displayed with option change. I am not getting error and not able to find what is mistake.
dashboard.php
<select id="employee">
<option value="" selected="selected"></option>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
$sql = "SELECT asset_type,department,cost FROM track_data";
$resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["asset_type"]; ?></option>
<?php } ?>
</select>
<div id="display" style="color: black">
<div class="row" id="heading" style="color: black"><h3><div class="col-sm-4"><strong>Employee Name</strong></div><div class="col-sm-4"><strong>Age</strong></div><div class="col-sm-4"><strong>Salary</strong></div></h3></div><br>
<div class="row" id="records" style="color: black"><div class="col-sm-4" id="emp_name"></div><div class="col-sm-4" id="emp_age"></div><div class="col-sm-4" id="emp_salary"></div></div>
</div>
<script type="text/javascript">
$(function () {
// $("#show_table").show();
$(document).ready(function(){
// code to get all records from table via select box
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'id='+ id;
$.ajax({
url: 'getEmployrr.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#emp_name").text(employeeData.asset_type);
$("#emp_age").text(employeeData.department);
$("#emp_salary").text(employeeData.cost);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
}
}
});
})
});
});
</script>
getEmployrr.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
if($_REQUEST['id']) {
$sql = "SELECT asset_type,department,cost FROM track_data WHERE id='".$_REQUEST['id']."'";
$resultset = mysqli_query($con, $sql) or die("database error:". mysqli_error($con));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
I am getting the head but not able to get the values inside the div. I am not getting any type of errors but values are not displaying. How can I solve the issue.
In first SQL query :
$sql = "SELECT asset_type,department,cost FROM track_data";
You don't select id, try to add it to your query :
$sql = "SELECT id,asset_type,department,cost FROM track_data";
I am trying to implement a dynamic drop-down list using Ajax and PHP. Based on the index value in the first option list, second one should give me list of names with that id.
select1.php :
<html>
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch1.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Dynamic Select Option Menu Using Ajax and PHP</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select ID</option>
<?php
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select distinct id from test";
$select= $conn->query($sql);
if ($select->num_rows > 0) {
while($row = $select->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['id']."</option>";
//echo "<option value=>".$row['id']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
<select id="new_select">
</select>
</div>
</center>
</body>
</html>
fetch1.php
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['get_option'];
//echo '$id';
$sql = "select id, name from test where id='$id'";;
$find= $conn->query($sql);
if ($find->num_rows > 0) {
while($row = $find->fetch_assoc()) {
//echo "<option>".$row['name']."</option>";
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
} else {
echo "0 results";
}
exit;
}
?>
My database looks something like this :
SELECT * from test;
id name
1 Name1
2 Name2
1 Name3
The first drop down works just fine. However the second drop down isn't working.
I have attached the screenshot of it as well. Is there a problem in sending data across the files or what? Not able to figure out where has the code gone wrong.
For the second option list, when I have selected 1, I should be getting Name1 and Name3 as options but I get none.
EDIT: Corrected javascript in select1.php
You are setting the content for new_select with the wrong variable.
It should be response rather than val
Change to:
document.getElementById("new_select").innerHTML=response;
And assign value to your return options.
Like:
echo "<option value='".$row['id']."'>".$row['name']."</option>";
And change your sql string to the following for the above to work.
$sql = "select id, name from test where id='$id'";
And make sure your jquery.js include is being loaded.
Add value to the Option in selectbox, right now there is no value passing from the fetch_select()
i have a table that displays data searched.
what i want to happen is when after i click the row, that data from that row clicked will be displayed in a form.
displaying the table:
search.php
echo '<table id="patientTable" class="w3-table-all w3-hoverable">'
echo '<tr class="w3-yellow"><th>Admission No</th><th>Hospital No</th><th>Patient Name</th></tr>';
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) ) {
echo '<tr onclick=patientClick(this)>';
foreach($row as $key=>$value) {
echo '<td>',$value,'</td>';
//echo $i;
}
echo '</tr>';
}
echo '</table><br />';
the script to attempt to connect to form
function patientClick(x){
var rowInd = x.rowIndex;
var adNo = document.getElementById("patientTable").rows[rowInd].cells[0].innerHTML
var hosNo = document.getElementById("patientTable").rows[rowInd].cells[1].innerHTML;
var patname = document.getElementById("patientTable").rows[rowInd].cells[2].innerHTML;
alert(adNo +"-"+ hosNo +"-"+ patname);//check to display row content
var jsObj = {patname:patname, adNo:adNo, hosNo:hosNo}
$.post('addPN.php', {data:jsObj}, function(data){
$('#displayPatient').html(data);
});
}
the form to display so to save more data
addPN.php
<?php
$arr = json_decode(json_encode($_POST["data"]),true);
$adNo = $arr[0]['adNo'];
$hosNo = $arr[1]['hosNo'];
$patname = $arr[2]['patname'];
echo $adNo;//check to display
echo $hosNo;//check to display
echo $patname;//check to display
?>
<html>
<body>
<form action = "savePN.php" id = "savePNotes" method = "POST">
<input type = "submit" id = "updateButton" value = "Save">
<input type = "text" readonly = "true" id = "adNo" name = "adNo" value = "<?php echo $adNo;?>">
<input type = "text" readonly = "true" id = "hosNo" name = "hosNo" value = "<?php echo $hosNo;?>">
<input type = "text" readonly = "true" id = "patname" name = "patname" value = "<?php echo $patname;?>">
<input type = "text" id = "cn" name = "cn" placeholder = "Contact Number">
<input type = "text" id = "cadd" name = "cadd" placeholder = "Address">
<input type = "text" id = "ctype" name = "ctype" placeholder = "Type">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
this is a bad practice using php as a client, but ajax is one way communication that you cant redirect instantly in serverside
function patientClick(x){
var rowInd = x.rowIndex;
var adNo = document.getElementById("patientTable").rows[rowInd].cells[0].innerHTML
var hosNo = document.getElementById("patientTable").rows[rowInd].cells[1].innerHTML;
var patname = document.getElementById("patientTable").rows[rowInd].cells[2].innerHTML;
alert(adNo +"-"+ hosNo +"-"+ patname);//check to display row content
//here you must construct some JSON object for your data
var jsObj = { pathname: pathname,
adNo: adNo,
hosNo: hosNo }
$.post('searchPatient.php', JSON.stringify({ data : jsObj}) , function(data){
$("#displayPatient").html(data);
});
}
in your server side you should decode your json
use this
$data = json_decode($_POST["data"])
echo $data["adNo"];
and i think you structure is no good and i think its not possible to do what you wanted to do because the form are from php and different file maybe its possible if you use just normal html form so can easily manipulate the form using DOM
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function() {
var $article = null;
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php");
});
});
</script>
This is what I am currently doing, I am loading the php.php script, instead I want to pass the value of $categoryName to the WHERE clause in my query so it's like this:
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$categoryName'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
The way this should work is, the first select box is populated by php on my server showing a list of categories. A user selects a category from that box and onchange, a second select box is created, added to the form, and will query, to populate all of the business name's listed in my database that share a category(i.e the selectedindex from the first box) Can you help me change this to work how I need it to?
UPDATE: This is the updated code, now the second select box never loads.
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function () {
var $article = null;
$('#category').change(function () {
var categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo ('.query');
$("#business").load( "php.php",
data:{myVar:$categoryName}
);
}
});
});
</script>
Heres the php.php
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$myVar = $_GET["myVar"];
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$myVar'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
As seen below you can make a data object with one parameter myVar
JS:
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php",
data:{myVar:$categoryName}
);
});
Then get the variable in PHP like this
PHP:
$con = mysqli_connect(,,,,);
$myVar = $_GET["myVar"];
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
peace be with you All, i am new to using Ajax , the issue is, i am having 3 drop down lists connected to a database, the first one is "name" and the second one is "age" and the third one is "country"! so, i have connected to the database, and retrieved data from it in the first list "name" and then using Ajax, i have successfully retrieved matching data after selecting any option of first list and put them into the second list called "age", the problem is that when i use a very exact same way with the second list called "age" to retrieve matching data into third list called "country" it doesn't work! so please help me cuz, i am using this example to learn Ajax and then apply on a larger real project!
here is the code :-
firstly, the home.php page:-
<?php
include "config.php";
?>
<html>
<head>
<script type="text/javascript">
function agematch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('age').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'connection.inc.php?name='+document.ajax.name.value, true );
xmlhttp.send();
}
function countrymatch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('country').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value, true );
xmlhttp.send();
}
</script>
</head>
<body>
<form id="ajax" name="ajax" >
Choose your name : <select name="name" id="name" select="selected" onchange="agematch();"> <option> </option>
<?php
$query = "SELECT DISTINCT name FROM info";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo"<option value ='".$row[0]."'> '".#$row[0]."'</option>";
}
?>
</select>
Age : <select id="age" name="age" onchange="countrymatch();"> </select>
country : <select id="country" name="country"> <option> </option> </select>
</form>
</body>
</html>
now, the page for first Ajax call :-
<?php
include "config.php";
echo " <option> </option> " ;
if(isset( $_GET['name']) ) {
#$name = $_GET['name'];
}
$query = "SELECT age FROM info WHERE name = '".#$name."' ";
$result = mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value ='".$query_row[0]."'> $query_row[0]</option> ";
}
?>
Now, with the page for the second Ajax call for the third drop menu :-
<?php
include "config.php";
if (isset( $_GET['age']) ) {
#$age=$_GET['age'];
}
$query = "SELECT country FROM info WHERE name='".#$name."' AND age='".#$age."' ";
$result= mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value = '".$query_row[0]."'> $query_row[0] </option> ";
}
?>
so as you see, here is the code, and of course i am connected to the database through a page called "config.php", so i want you to help me to solve this issue and retrieve the data from database into the third drop down list "country".
Thanks in Advance!
Ok, Musa here is the edit :-
function countrymatch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('country').innerHTML = xmlhttp.responseText;
}
}
var age = encodeUriComponent(document.ajax.age.value),
var name = encodeUriComponent(document.ajax.name.value),
xmlhttp.open('GET', 'country.inc.php?age='+age+'&name'+name, true );
xmlhttp.send();
}
and also :-
<?php
include "config.php";
if (isset($_GET['age'], $_GET['name']) ) {
#$age=$_GET['age'];
#$name = $_GET['name'];
}
$query = "SELECT country from info where name='".#$name."' AND age='".#$age."' ";
$result= mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value = '".$query_row[0]."'> $query_row[0] </option> ";
}
?>
I don't get any error messages, i am sure your point is right but this solution didn't work unfortunately! thank you so much for helping me :)
You didn't send the name in the second ajax request but you need it for your database query, so you'll need to send the name as well as the age in the ajax request. Also you aren't sanitizing your input, you must always validate user input, I'd also suggest not using mysql_*
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
var age = encodeURIComponent(document.ajax.age.value),
var name = encodeURIComponent(document.ajax.name.value),
xmlhttp.open('GET', 'country.inc.php?age='+age+'&name'+name, true );
if (isset($_GET['age'], $_GET['name']) ) {
$age = $_GET['age'];
$name = $_GET['name'];
...
}