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?
Related
I'm trying to pass select option value through url.selection value come from mysql table.i want to pass that driver name to another page.
<?php
//another select query goes here.
$query1= "SELECT * FROM driver WHERE status='Available'" ;
echo '<td>'.'<select name="driver">';
$result1= mysql_query($query1);
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="'.$row1["name"].'">'.$row1["name"].'</option>';
}
echo '</select>'.'</td>';
echo'<a rel="facebox" href=db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'>' . 'Confirm' . '</a>';
?>
Use jQuery.
Call change event of the drop down.
$(function(){
$("[name=driver]").die('change').live('change', function(){
var driver = $(this).val();
if (typeof driver !== 'undefined') {
window.location.href = 'YOUR_FILE.php?driver='+driver;
}
});
});
And
in your YOUR_FILE.php, get driver using $_GET['driver']
Or if you want the form to be more secure, take a hidden variable.
On change of driver, assign it the value of driver drop down.
And post the form.
In your PHP file, get it as $_POST['hid_driver'].
U can add onclick function for the select field, try this way
<?php
//another select query goes here.
$query1= "SELECT * FROM driver WHERE status='Available'" ;
echo '<td>'.'<select name="driver" onchange="window.location.href=\'db_confirm_booking.php?driver=' . $_POST['driver'] . '&id=\'+this.value">';
$result1= mysql_query($query1);
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="'.$row1["name"].'">'.$row1["name"].'</option>';
}
echo '</select>'.'</td>';
echo'<a rel="facebox" href=db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'>' . 'Confirm' . '</a>';
?>
try this code
<?php
//another select query goes here.
$query1= "SELECT * FROM driver WHERE status='Available'" ;
echo '<td>'.'<select name="driver"
onChange="window.location.href=this.value">';
$result1= mysql_query($query1);
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'">"'.$row1["name"].'">'.$row1["name"].'</option>';
}
echo '</select>'.'</td>';
echo'<a rel="facebox" href=db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'>
' . 'Confirm' . '</a>';
?>
example code
<select onChange="window.location.href=this.value">
<option value="www.google.com">A</option>
<option value="www.aol.com">B</option>
</select>
<select name="sel" id="sel" onchange="seturl(this.value)">
<option value=""></option>
</select>
<script>
function seturl(id)
{
document.forms[0].action="test.php?driver="+id;
document.forms[0].submit();
}
</script>
It will reload the page with driver name in url.
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.
I am trying to use a dynamically generated dropdown list to populate a table. I have a drop down list that is generated from my database (it grabs all the years available for a specific player). I want to be able to select a year from the dropdown and have it update my table. I have the dropdown being generated, but I am not able to get the selected value from the dropdown. I have code below that I found here, but it doesn't seem to work. Here is the code I have so far:
<input name="update" type="submit" value="Update" />
</form>
<p></p>
<form action="player_login.html">
<input type="submit" value="Logout" />
</form>
</div>
<div style="float: left">
<p></p>
<h1>Player Stats</h1>
<table width="300" border="1" cellpadding="2" cellspacing="2">
<?php
// get "id" field from player table
$login_id = $_COOKIE["DB"];
$id = "select id from player where login_id='$login_id';";
$result1=mysql_query($id) or die('Select1 Query failed: ' . mysql_error());
$row = mysql_fetch_array($result1);
// create a dropdown from stats table in db
echo "--Select Year--";
$years_query = "select year from stats where player_id='$row[id]';";
$years = mysql_query($years_query, $connect);
// fill array with db info
$var = array();
while ($row2 = mysql_fetch_array($years))
{
$var[] = $row2['year'];
}
// create dropdown
echo'<select name="years" id="years">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select>';
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query) or die('Select2 Query failed: ' . mysql_error());
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
// create table with results
echo "<tr>";
echo "<td>Year</td>";
$j=1;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Total Points</td>";
$j=2;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>PPG</td>";
$j=3;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
?>
</table>
</div>
I see that you use $_POST and since form is not submitted and thus data of $_POST is not set. Best available option I have used to catch the event and send the AJAX Query fetch results and update it.
I have done this with the help of J Query as under
$('#years').change(function() {
$.ajax({
//request of AJAX
type : 'POST',
url : 'players_data.php',
dataType : 'json',
data: {
//Data with $_POST request
years : $('#years').val();
},
success: function(data){
//Things to be done with returned data
}
}};
Create a new file players_data.php and there you write the code for fetching data from the db as:
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query);
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
$return['year']=$line;
echo json_encode($return);
I see that you are using $_POST, and why do you don't use a form?
//This is for get the form
echo '<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>';
//create a form
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
// create dropdown; onchange will send the form when selected index changes...
echo '<select name="years" id="years" onchange="get_form(this).submit(); return false;">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select></form>';
And that's all! :D
I'm seeing too that you are using an unique form for update all the page... It's isn't work, because you only have a submit button and no more element in the form, please read that: http://www.w3schools.com/tags/tag_form.asp
From your code i can see that u want to get the value from the select box and immediately populate the table and display the results..use jquery to get the value of selected object and assign the javascript variable to a php variable. and insert into the db..
<script type="text/javascript">
$( "#years" ).change(function() {
var value=document.getElementById("years").value;
alert(value);
</script>
assign the variable to php and execute you php query.
<?php
$data = "<script>document.write(value)</script>";
//execute your query here..
?>
Also have a look at ajax..it does that so well...
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
}));
});
Following on from my question yesterday, I now have the code below somewhat successfully working. It allows me to change the first form item and submits it to 'process.php' in the background and turns the field green. However the trigger only works on the first form item, in this case "cstate". It doesn't trigger when "clocation" is changed. If you change clocation and then cstate then both form submit fine so it's simply that the .change function isn't triggering when clocation is changed. I'm not good enough at JS (total JS noob) to know why it isn't working so I'd appreciate any help you can give me.
Thanks!
$sql = "select * from `$table1`";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$carid = $row["car_id"];
$carnum = $row["carnum"];
$carlocation = $row["carlocation"];
$carstate = $row["carstate"];
$formname = "#form".$carid;
print '<script type="text/javascript">';
print " var cnum;";
print " cnum = '$formname',";
print "
$('form').change(function()
{
console.log(cnum);
$.ajax({
type: 'post',
url: 'process.php',
data: $(this).serialize(),
success: function() {
}
});
return false;
});
</script>";
echo "<table>";
echo "<tr id='$carid'>";
echo "<td>$carnum</td>";
echo "<td><form action='' method='post' id='form$carid'>";
echo "<select id='popup' name='cstate'>";
echo "<option value='In-Service-Bay'>In Service Bay</option>";
echo "<option value='Awaiting-Service'>Awaiting Service</option>";
echo "<option value='Service-Complete'>Service Complete</option>";
echo "</select></td>";
echo "<select id='popup' name='clocation'>";
echo "<option value='Carpark-1'>Carpark-1</option>";
echo "<option value='Carpark-2'>Carpark-2</option>";
echo "<option value='Carpark-3'>Carpark-3</option>";
echo "</select></td>";
echo "</form></tr>";
}
echo "</table>";
Use .on() and wrap code inside document.ready.
$(document).ready(function(){
$('form').on('submit',function()
{
//code here
});
});
also put this code outside the while loop. Also form does not have change event try using .submit()
Solved it by using a separate form for each input selection. Works brilliantly now.
Thanks to all those that tried to help.
Adam