get php variable from dropdown without page submission - php

I am trying to get a value from a dropdown menu and pass it as a php variable and echo it (on the same page).
The dropdown displays the name of users, but select their username, which I want to echo. The purpose it to use the variable to perform other tasks, if I can echo it successfully.
I have used jquery and ajax to get the variable, without submitting the page. But I am unable to get the php variable.
I have read several examples, and used them, but somehow my code is not working.
Can anyone please suggest where is the mistake?
Here is my code:
Test2.php
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>
</select>
</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {
var user = $(this).val();
$.ajax({
url:"test2.php",
data:{username : user},
type:'POST',
success:function(response) {
$("#usermame").html(response);
}
});
});
});
</script>
<?php
if (isset($_POST['username'])){
$username = $_POST['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?>

<?php
if (isset($_GET['username'])){//only echo user name if requested from js do not include header or footer
$username = $_GET['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}else{//you can include here your headers
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>
</select>
</td> </tr> <tr><td> <span id="username">
<?php if (isset($_POST['username'])){//show if submitted from html form
$username = $_POST['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?> </span></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {
var user = $(this).val();
$.ajax({
url:"test2.php?username="+user,
success:function(response) {
$("#username").html(response);
}
});
});
});
</script>
<?php
//you can include here your footers
}
?>

Your success handler is printing the request content in a html element with id username that do not exists on the page (at least not on this snippet)
success:function(response) {
$("#usermame").html(response);
}
Try to make the POST request to a different file because, in your case, the printed content will include the select (and the db request) again.

Related

Dependent combo boxes in PHP and Ajax

I need help with my code. I want to select values from the database based on the first combo box selection.
The first combo box has subject ID, which I want to use in my SQL to find the value of the second combo box.
<form class ="form_group" id="form1" enctype="multipart/form-data" method="POST" action="uploadstudent.php">
StudentID:<br>
<input type="text" name="StudentID" value="<?php echo $_SESSION['login_user'];?>"readonly>
<br><br>
Subject ID:<br>
<select id="soflow" name="SubjectID" onChange="getState(this.value);">
<option>
<?php
mysql_connect("localhost", "id503120_course", "12345678");
mysql_select_db('id503120_course_db');
$StudentID=$_SESSION['login_user'];
$Course = mysql_query("SELECT course FROM student WHERE StudentID = '".$StudentID."'");
$result = mysql_fetch_assoc($Course);
$newcourse = implode($result);
$query=mysql_query("SELECT SubjectID FROM subjects WHERE Course= '".$newcourse."' AND SubStatus = 'Y'");
if(!$numrows=mysql_num_rows($query)==0)
{
while($row=mysql_fetch_assoc($query))
{ ?>
<option value="<?php echo $row['SubjectID']; ?>">
<?php echo $row['SubjectID']; ?>
</option>
<?php }
}
else{
echo "No submissions are currently open for you";
}
?>
</select>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "submission.php",
data:'SubjectID='+val,
success: function(data){
$('#soflow2').html(data);
}
});
}
</script>
Assign number: <br><select id="soflow2" name="AssessmentNum">
<option>
<?php
mysql_connect("localhost", "id503120_course", "12345678");
mysql_select_db('id503120_course_db');
if(!empty($_POST["SubjectID"])) {
$query ="SELECT AssignNum FROM subjects WHERE SubjectID = '".$_POST['SubjectID']."'";
while($row=mysql_fetch_assoc($query))
{ ?>
<option value="<?php echo $row['AssignNum']; ?>">
<?php echo $row['AssignNum']; ?>
</option>
<?php }
}
?>
Here in assign number, I am not able to view any information at all.
Please help me.
The problem is in the parameter SubjectID in the ajax request. try this:
function getState(val) {
$.ajax({
type: "POST",
url: "submission.php",
data:{'SubjectID' :val},
success: function(data){
$('#soflow2').html(data);
}
});
}

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

Submit form in div with ajax, return php in div without refresh

I have an index page with three buttons at the top. On the click of each button a php file is loaded into the main div. One of these buttons loads a form that users fill out and submit. On submitting of the form I need it to not refresh the page and to load the resulting data into a div on the form page...not the main div.
If I load the form page on it's own (ie, not by clicking on the button, but just typing in the address of the form itself)...everything works fine. The form validation works, it submits without a refresh and the resulting data is returned into the results div on the form.
However, I load the index page and click on the button to load the form. The form loads correctly, but when I click submit it just refreshes the page...which causes the form to disappear since the div into which it is loaded is originally hidden. Also, the form doesn't validate and doesn't execute the php action.
Again, the form and its associate php work perfectly on their own. The issue only comes up when I load the form in the index page. So I'm assuming that this issue has something to do with me loading it into a div on the index page. Any help would be greatly appreciated.
Index code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="header">
<center><h2>OMS Tutoring Database</h2></center>
</div>
<div id="navbar">
<center>
<button class="navbutton" id="buttonview" type="button">View Tutoring Lists</button>
<button class="navbutton" id="buttonadd" type="button">Add Students</button>
<button class="navbutton" id="buttonadmin" type="button">Admin</button>
</center>
<br>
</div>
<div id="content"></div>
<script>
$(document).ready(function() {
$('#buttonview').click(function(){
$('#content').load('tutoring.php', function(){
});
});
$('#buttonadd').click(function(){
$('#content').load('addtest.php', function(){
});
});
$('#buttonadmin').click(function(){
$('#content').load('admin.php', function(){
});
});
});
</script>
</body>
</html>
Form Code
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addstudent").validate({
debug: false,
rules: {
studentid: "required",
teacher: "required",
assignment: "required",
date: "required",
},
messages: {
studentid: "Please enter the student's ID number.",
teacher: "Please enter your name.",
assignment: "Please select a tutoring assignment.",
date: "Please select a day.",
},
submitHandler: function(form) {
$.ajax({
url: 'add.php',
type: 'POST',
data: $("#addstudent").serialize(),
success: function(data) {
$("#studentid").val("");
$('#studentid').focus();
$("#results").empty();
$("#results").append(data);
}
});
return false;
}
});
});
</script>
</head>
<title>OMS Tutoring - Add Student</title>
<body>
Use this form to add students to the tutoring list.
<p>
<div style="float:left;width:100%;margin-bottom:10;">
<div>
<form name="addstudent" id="addstudent" action="" method="post">
<fieldset><legend>Add student to tutoring list</legend>
<div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>
<div><label for="day">Date</label><select name="date" id="date">
<option value="">Please select a day</option>
<option value="mon">Monday <? echo $monday; ?></option>
<option value="tue">Tuesday <? echo $tuesday; ?></option>
<option value="wed">Wednesday <? echo $wednesday; ?></option>
<option value="thu">Thursday <? echo $thursday; ?></option>
<option value="fri">Friday <? echo $friday; ?></option>
</select></div>
<div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
<option value="">Please select an assignment</option>
<option value="att">Activity Time</option>
<option value="acc">ACC</option>
<option value="tech">ACC Tech </option>
<option value="ast">After School</option>
</select></div>
<div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>
<input type="submit" name="submit" value="submit">
</fieldset>
</form></div></div>
<div id="results" style="margin-left:4;width:350;"><div>
</body>
</html>
Form processing php code:
<?php
$mysqli = new mysqli('localhost', 'xxx', 'xxx', 'xxx');
$studentid = $_REQUEST['studentid'];
$day = $_REQUEST['date'];
$assignment = $_REQUEST['assignment'];
$teacher = $_REQUEST['teacher'];
$dayquery = $mysqli->query("SELECT date FROM days WHERE day='$day'");
$dayresult = $dayquery->fetch_array();
$date = array_shift($dayresult);
$timestamp = date('Y-m-d H:i:s');
$mysqli->query("INSERT INTO assign (id, assignment, assignteacher, date, timestamp)
VALUES ('$studentid', '$assignment', '$teacher', '$date', '$timestamp')");
$namequery = $mysqli->query("SELECT first, last FROM students WHERE students.id='$studentid'");
$nameresult = $namequery->fetch_array();
echo $nameresult['first'].' '.$nameresult['last'].' successfully added.';
$teacherquery = $mysqli->query("SELECT assignteacher FROM assign WHERE id='$studentid' AND date='$date'");
$rowcount = $teacherquery->num_rows;
if ($rowcount > 1) {
while ($row = $teacherquery->fetch_array()) {
$teachernames[] = $row[0];
}
$teachers = implode(', ', $teachernames);
echo '<br><br>Caution: '.$nameresult['first'].' '.$nameresult['last'].' has already been added by the following teachers: '.$teachers.'. ';
echo 'They may have precedence.';
}
else {
}
$alreadyadded = $mysqli->query("SELECT assign.id, students.first, students.last, assign.assignment, assign.assignteacher FROM assign
LEFT JOIN students
ON assign.id=students.id
WHERE assign.date='$date' AND assign.assignteacher='$teacher'
ORDER BY assign.assignment ASC, students.last ASC");
echo '<br><br><br>You already have the following student(s) assigned to tutorials on this day';
echo '<table border="1">';
while ($row = $alreadyadded->fetch_array()) {
echo '<tr><td>'.$row['id'].'</td><td>'.$row['first'].'</td><td>'.$row['last'].'</td><td>'.$row['assignment'].'</td></tr>';
}
?>
When you load the form into your page using the load method, most browsers delete the <head> tag.
As from the jquery website:
During this process, browsers often filter elements from the document
such as <html>, <title>, or <head> elements. As a result, the elements
retrieved by .load() may not be exactly the same as if the document
were retrieved directly by the browser.
So, include your javascript in the main page instead of in the form page, or manually add the javascript to your main page dynamically.

Populate Text Input Via Dropdown Jquery

I pull data from a MYSQL database to populate a Drop down
<td class="<?php print $Bank_ca_error;?>">Bank Name</td> <td> <select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> <option><?php print $_SESSION['Bank_ca'] ;?></option> <?php //Get Data to populate drop down $BankQuery = "SELECT BankName FROM tblbank ORDER BY BankName"; $BankResult = mysql_query ($BankQuery); While($nt=mysql_fetch_array($BankResult)) { print"<option $nt[BankName]>$nt[BankName]</option>"; } ?> </select> </td>
I would like based on the value selected populate a text input. So Basically Select the Bank from the List and have it autopopulate the Universal Branch Code in the text input.
I saw an example using Jquery, But I am a complete noob when it comes to this and I cannot get it to work properly
I added the following in the Head section
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#Bank').live('change', function(event) { $.ajax({ url : 'getData.php', type : 'POST', dataType: 'json', data : $('#myform').serialize(), success: function( data ) { for(var id in data) { $(id).val( data[id] ); } } }); }); }); </script>
I then Added this into the getData.php file
<?php include "../../../includes/dbinfo.inc"; //Connect to database mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database"); $BankName = $_POST['Bank']; // Selected Bank $query = "SELECT * FROM tblbank WHERE BankName ='{$BankName}'"; $result = mysql_query($query); $row = mysql_fetch_array($result) $BranchCode = $row['UniversalCode']; $arr = array( 'input#BranchCode' => $BranchCode ); echo json_encode( $arr ); ?>
and added the Following to around the inputs and dropdown concerned
<form id='myform'> </form>
I tried to use a solution elsewhere on this site but could not get it to work
Your assistance is greatly appreciated
If I understand correctly what you're trying to do, then you do not need ajax, try something like this
<?php
include "../../../includes/dbinfo.inc";
//Connect to database
mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database");
$res = mysql_query("SELECT UniversalCode, BankName FROM tblbank ORDER BY BankName");
while($row = mysql_fetch_assoc($res)) {
// associative array of banks
$banks[$row['UniversalCode']] = $row['BankName'];
}
?>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#Bank').change( function() {
// enter in an empty field code of the selected bank
$('#UniversalCode').val( $(this).val() );
});
});
</script>
<td class="<?php print $Bank_ca_error;?>">Bank Name</td>
<td>
<select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/>
<? foreach($banks as $code=>$name) { ?>
<option value="<?=$code?>"><?=$name?></option>
<? } ?>
</select>
<input value="" id="UniversalCode">
</td>

Post result from a query via php in same page with Ajax

I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.

Categories