I want to create a dynamic drop down where the options of the second drop down changes after the selection of the first drop down.
The test.php file
<?php
$con=mysqli_connect("localhost","******","****","******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM countries");
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";
}
?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax
<script type="text/javascript">
function get_states() { // Call to ajax function
var country = $('#country').val();
var dataString = "country="+country;
$.ajax({
type: "POST",
url: "getstates.php", // Name of the php files
data: dataString,
success: function(html)
{
$("#get_state").html(html);
}
});
}
</script>
<?php
mysqli_close($con);
?>
and the gestates.php is:
<?php if ($_POST) {
$country = $_POST['country'];
if ($country != '') {
$sql1 = "SELECT * FROM states WHERE country_id=" . $country;
$result1 = mysql_query($sql1);
echo "<select name='state'>";
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result1)) {
echo "<option value='" . $row['id'] . "'>" . $row['state_name'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
However the above code does not work!
on change on first drop-down you need to make an ajax call which will get the options and you can then populate the next drop-down
Try adding single quotes around $country
$sql1 = "SELECT * FROM states WHERE country_id='" . $country . "'";
or
$sql1 = "SELECT * FROM states WHERE country_id='$country'";
EDIT: Also, you can only echo one result. Your second echo will be ignored by Jquery as the first will be considered a success.
You should format your results differently.
Perhaps a json encoded array.
In your php:
while($row = mysql_fetch_array($result1))
{
$data[$row['id']] = $row['state_name'];
}
echo json_encode($data);
In your Jquery set dataType: 'json'
$.each(html,function(key,value){
$("#get_state").append($('<option>',{
value:key,
text: value
}));
});
Related
I have some names of places inside a select. Some of this names have apostrophe.
When user makes his choice with that select, Ajax makes a query to a table to find occurrencies of shops that match that location. My code is this:
<?php
echo "<select id='location' name='location'>";
echo "<option value='' selected>Select a location</option>";
$sql = "SELECT * FROM locations_list ORDER BY location_name;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['location_name'] . "'>". $row['location_name'] . "</option>";
}
}
echo "</select>";
echo "<select id='shop' name='shop'>";
echo "<option value='' selected='shop'>Select location first</option>";
?>
<script>
$(document).ready(function(){
$('#location').on('change',function(){
var locationID = $(this).val();
if(locationID){
$.ajax({
type: 'POST',
url: 'extract_shops.php',
data: {'location': locationID},
success:function(html){
$("#shop").html(html);
}
});
}else{
$('#shop').html('<option value="">Select a location first!</option>');
}
});
});
</script>
<?php
echo "</select>";
Things run smoothly when the locations don't have apostrophe in their name. In such cases, Ajax passes location name to extract_shops.php (which has a simple "SELECT * FROM shops WHERE location = '$passedlocationname';") and gets back a list of shops.
But when location has an apostrophed name, Ajax does not pass anything to extract_shops.php. I have put an if inside extract_shops.php that returns this info inside the second select in case Ajax doesn't pass anything.
Where am I wrong?
I am using more than one dropdown in may page the first being:-
function createCFAList()
{
$ajax = false;
if(isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['cl']))
{
$SelectedCFAName = $_GET['cl'];
$ajax = true;
}
$sql = "SELECT DISTINCT `cfalist`.`CFA`
FROM `amwplist`
INNER JOIN `cfalist` ON `cfalist`.`CFA_ID` = `amwplist`.`CFA_ID`";
$result = mysql_query($sql);
$CFAlist = "<select id='cfa5' name='cfa5'>";
while ($row = mysql_fetch_array($result)) {
$CFAlist = $CFAlist . "<option value='" . $row['CFA'] ."'>" . $row['CFA'] ."</option>";
}
$CFAlist = $CFAlist . "</select>";
return ($CFAlist);
}
The Second list being:-
function createStatusList()
{
$ajax = false;
if(isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['ss']))
{
$SelectedStatus = $_GET['ss'];
$ajax = true;
}
$sql = "SELECT `Status_ID`,
`Status_Type`
FROM `workstatuslist` ";
$result = mysql_query($sql);
$Statuslist = "<select id='status4' name='status4'>";
while ($row = mysql_fetch_array($result)) {
if($row['Status_Type'] == "BOO in Progress")
{
$Statuslist = $Statuslist . "<option selected='" . $row['Status_Type'] ."'>" . $row['Status_Type'] ."</option>";
}
else
{
$Statuslist = $Statuslist . "<option value='" . $row['Status_Type'] ."'>" . $row['Status_Type'] ."</option>";
}
}
$Statuslist = $Statuslist . "</select>";
return ($Statuslist);
}
These two functions are placed in function.php and are called from AMWP.php to display the Dropdown. The selected options are stored in variables
global $SelectedStatus and global $SelectedCFAName
using the following script in AMWP.php:-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -->
<script>
$('#status4').change(function()
{
var status4 = $('#status4').val();
var req = $.get('functions.php', {ss: status4, action: 'ajax'});
});
$('#cfa5').change(function()
{
var cfa5 = $('#cfa5').val();
var req = $.get('functions.php', {cl: cfa5, action: 'ajax'});
});
</script>
How may I store the Selected Option onChange to the variables declared global $SelectedStatus and global $SelectedCFAName
and then use them to create SQL Statement like whenever the Selected option is changed by the user
$sql="SELECT * FROM abc WHERE status LIKE $SelectedStatus AND cfa LIKE $SelectedCFAName";
I have found the solution at this URL
SourceCodester Dot Com
Found One more good sample source at this link
PHP Jquery Dropdown sample. Good One
I know that my question may be duplicate, but I've looked through a ton of questions with the same problem, but none of the solutions worked for me.
It's pretty simple, get the item-id value and POST it to del.php.
I can't get the POST value in the php after the click.
<?php
include '../include/db.php';
$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
$("tr").click(function() {
var id = $(this).find('.item-id').text();
$.post('del.php',{id: id},function(json){
window.location.href = "http://localhost/unesc/3/admin/del.php";
}, "json")
});
</script>
del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo $id;
} else {
echo "erro";
}
?>
The del.php just get the $_post['id'] and echo it.
The window.location is there so i won't have to enter the address manually.
The trigger may not be necessarily a Click, it can be a Button, woks just fine for me too.
EDIT: got the POST running with $.ajax, but now, with firebug i noticed that the post in del.php keeps returning empty.
EDIT2: got the del.php post response, but as an error, it says that 'id' don't exist.
If THIS is what you need here is the code of both pages I used
del2.php
<script type="text/javascript" language="javascript" src="jquery.min.js"></script>
<?php
//include '../include/db.php';
include 'includeconnect.php';
//$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
$result = mysql_query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysql_fetch_array($result))
{
echo "
<table border='1'>
<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>
</table>
</br>";
}
echo"<div id='show_responce'>I am a text on page del2.php and I am pretty much useless apart from showing you where the responce will display</div>"
?>
<script type="text/javascript">
$("tr").click(function() {
var rep = $("#show_responce");
var id = $(this).find('.item-id').text();
var dataString = 'id=' + id;
$.ajax({
type: 'post',
url: 'del.php',
data: dataString,
success: function(html) {
rep.empty().append(html);
rep.fadeIn("slow")
}
});
});
</script>
Here is your modified del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo "I am coming from del.php and the ID you clicked on is $id";
} else {
echo "error";
}
?>
By the way because of my account's low reputation I could not ask you what was you trying to do with this window.location but whatever. Instead of what you asked for which was basically to make sure that del.php gets the value of id as you will see I displayed it on del2.php which is the page I am making the request from.
$( "table > td" ).find( ".item-id" ).val();
or
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr id='row'>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script>
var id = [];
var values = [];
$("#row > .item-id").each(function(index){
id.push($(this).attr("id")); // [a,b,c,....]
values.push($(this).text()); //[ Dummy1, Dummy2, Dummy3, Dummy4,..]
});
</script>
Possible errors:
}, "json") here last argument means, that function expects you return valid JSON string from del.php file.
After window.localtion.href you can't access previous data, because it redirects to another page, and thus you loose all your previous data.
Basically, this code gets info from id.php by studentid and returns address, document cost, etc The code is returned when the button student id is clicked but only for the first row. The second row does not return any data and i cant seem to figure out the problem. please help.
<div id="briefinfo" style="display:inline-block;text-align:center;margin-left:20px;">
<?php require_once("db.php");
if ($result = $mysqli->query("SELECT * FROM requests WHERE status = 1 ORDER BY id"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo "<div id='thumbnail'>";
echo " ". $row->lastname;
echo " ". $row->firstname;
echo "</div>";
echo "document id:" . $row->id;
echo "<br>";
echo "requested: " . $row->document;
echo "<br>";
if ($row->paidstatus == 1){
echo "payment status: paid";
}
else{
echo "payment status: not paid";
}
echo "<br>";
echo "<input type='button' value='$row->student_id' id='studentid'/>";
/*echo "<td>" . $row->document . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "<td><a href='unverify.php?id=" . $row->id . "'>unverify</a></td>";
echo "<td><a href='comments.php?id=" . $row->id . "'>comment</a></td>";
echo "<td>" . $row->paymentamount . " pesos";"</td>";
echo "<td><a href='paymentamount.php?id=" . $row->id . "'>set amount</a></td>";*/
}
}
else
{
echo "No results to display!";
}
}
else
{
echo "Error: " . $mysqli->error;
} ?>
</div>
This is the JS
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
//in your Javascript, put
$(document).ready ( function () {
$("#studentid").click (function(){
var studentid = $(this).val();
$.ajax({
type: 'POST',
url: 'id.php',
data: {
id: studentid
},
success: function(response) {
$("#moredata").html(response);
}
});
});
});
</script>
this id.php
<?php
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
require_once("db.php");
$id = $_POST['id'];
if ($result = $mysqli->query("SELECT * FROM requests WHERE student_id=$id"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->paymentamount . " pesos";
echo "<br>";
echo $row->address;
echo "<br>";
echo $row->address2;
echo "<br>";
echo $row->country;
}
}
else
{
echo "No results to display!";
}
}
else
{
echo "Error: " . $mysqli->error;
}
?>
First row of input button shows more data in when clicked the button. Second row does not display anything anymore. help
For following statement in while loop you should use class instead of id. You should not use same ID for multiple element.
echo "<input type='button' value='$row->student_id' class='studentid'/>";
And in your jquery script you should call it this way:
<script>
//in your Javascript, put
$(document).ready ( function () {
$(".studentid").click (function(){
var studentid = $(this).val();
$.ajax({
type: 'POST',
url: 'id.php',
data: {
id: studentid
},
success: function(response) {
$("#moredata").html(response);
}
});
});
});
</script>
I have a drop down list called courses. When the user chooses a course, I should show him information about the teacher that gives this course. So, on change I need to get the value selected, and show him the results generated from an sql query.
This is my php code:
$sql= "SELECT id, course_period_id from schedule WHERE STUDENT_ID='$_SESSION[student_id]'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["id"];
$course_period_id=$row["course_period_id"];
$course= DBGet(DBQuery("SELECT title FROM course_periods WHERE course_period_id='$course_period_id'"));
$options.="<OPTION VALUE=\"$course[1]['TITLE']\">".$course[1]['TITLE'].'</option>';
}
echo '</TD></TR></TABLE>';
echo "<SELECT>
<OPTION VALUE=0>Choose
$options
</SELECT>";
echo '</TD></TR></TABLE>';
I want to use "href", as I created a php file "teachers_info.php" with the following code:
if(!empty($_GET['Course']))
{
$sql="SELECT teacher_id FROM course_periods where title= '$course'";
$teacher_id= DBGet(DBQuery($sql));
$result= DBGet(DBQyery(" SELECT first_name, last_name, phone, email FROM staff WHERE staff_id = '$teacher_id[1]['teacher_id']'"));
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Phone</th>
<th>E-mail</th>
</tr>";
echo "<tr>";
echo "<td>" . $result[1]['first_name'] . "</td>";
echo "<td>" . $result[1]['last_name'] . "</td>";
echo "<td>" . $result[1]['phone'] . "</td>";
echo "<td>" . $result[1]['email'] . "</td>";
echo "</tr>";
echo "</table>";
}
How can I do this?
Thanks :)
Ok this is a bad approach, for multiple reasons:
This should be done using ajax
Don't use $_SESSION for this
I'll help you out. The first thing you need is jquery. You can find it here: http://jquery.com .
Next take a look at this picture to understand how ajax works:
In short, ajax is used to make calls to the server and update the page with the response without reloading. In your case, you will make a call to the server, send course and receive the results.
Once you have jquery set up, you have to write this:
$(function(){
$("select").on("change", function(){
var value = $(this).value(); //get the selected id
$.get("requesturl.php", {course: value}, function(){
// do something with the response
}, "json");
})
})
The requesturl.php file would look as follows:
$course = $_GET["course"]
if($course){
//execute Database query and store it in $result
echo json_encode($result);
}
you can modify this code.
myform.php
<script type="text/javascript">
$(document).ready(function(){
//Below line will get value of Category and store in id
$("#Category").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "GET",
url: "Ajax_SubCategory.php",
data: dataString,
cache: false,
success: function(html)
{
//This will get values from Ajax_SubCategory.php and show in Subcategory Select option
$("#SubCategory").html(html);
}
});
});
});
</script>
<form>
<?php
mysql_connect("localhost","root","") or die("error connect");
mysql_select_db("test") or die(" error database");
echo "<select name='Category' id='Category'>";
echo "<option value='' disabled='' selected='' >--Select Category--</option>";
$q6=mysql_query("select DISTINCT Category from category");
while($r6=mysql_fetch_array($q6))
{
echo "<option value='$r6[0]' >$r6[0]</option>";
}
echo "</select>";
echo "<select name='SubCategory' id='SubCategory'>";
echo "<option value='' disabled='' selected='' >--Select Sub Category--</option>";
echo "</select>";
?>
</form>
Ajax_SubCategory.php
<?php
mysql_connect("localhost","root","") or die("error connect");
mysql_select_db("test") or die("error database");
if($_GET['id'])
{
$id=$_GET['id'];
$sql=mysql_query("select SubCategory from category where Category='$id'");
while($row=mysql_fetch_array($sql))
{
$data=$row['SubCategory'];
echo '<option value="'.$data.'">'.$data.'</option>';
//echo "<input type='checkbox' value='".$data."' >".$data.;
}
}
?>
Well if you want the PHP to get something you ned to post something. You either add a submit button or:
echo "<select name=\"course\" id=\"course\" onchange=\"this.form.submit()\">
<OPTION VALUE=0>Choose
$options
</SELECT>";
Then you can utilize if(!empty($_GET['Course'])) {
because $_GET[] need the form to be submited.