how to post data with ajax, php and bootstrap select - php

I am banging my head against a wall with this now so any help will go a long way with this one.
I am trying to get some data from a drop down list and update a database with the data selected.
This is my drop down list:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status[]">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
View Area
This is my ajax:
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: status},
success: function() {
"area switched"
}
});
});
and this is my page that is updating the databse (sim-area.php):
<?php
$userID = $user['userID'];
$selectedArea = $_GET['changeStatus'];
$queryAreaName = "
SELECT UserID, Name, U_NB, U_RTN
FROM Table
WHERE UserID = '$userID' AND Name = '$selectedArea'";
$getAreaname = sqlsrv_query($sapconn2, $queryAreaName);
$areaSwitch = sqlsrv_fetch_array($getAreaname, SQLSRV_FETCH_ASSOC);
$areaNB = $test2['U_NB'];
$areaRTN = $test2['U_RTN'];
//UPDATE TABLE
?>
No matter what I try I get an undefined error, I have changed it to hard code the values and in inserts fine, so I know everything is working fine, It just isn't passing the data through

Looks you are not passing data correctly to ajax call.
Below is updated code for dropdown (changed name of select and added id attribute):
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status" id="changeStatus">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
Updated code for jquery (changed code for passing value of data):
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: $('#changeStatus').val()},
success: function() {
"area switched"
}
});
});

Related

Not Getting a POST value from ajax

I have a select dropdown and a textfield in my form. So i tried using $.ajax whenever i choose a value in dropdown, the textfield will show an output based on the selected value from the dropdown. But im always getting an error undefined variable from ff.php. I tried to pin down the cause, and what i found is im not getting any POST value in ff.php. Any solution for this ? Thanks in advance.
Here is my code in prs.php
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "ff.php",
data:'productid='+val,
success: function(data){
$("#brandss").val(data);
}
});
}
</script>
<td><select name="drpcode" onchange="getState(this.value)" class="form-control name_list"><?php $drp = mysqli_query($conn,"SELECT productcode FROM products"); while ($dp = mysqli_fetch_array($drp)) {
?><option value="<?php echo $dp['productid']; ?>"><?php echo $dp['productcode']; ?></option><?php } ?></select></td>
<td><input type="text" id="brandss" name="brand" placeholder="Brand" class="form-control name_list" required value=""></td>
Here my codes in ff.php
<?php
require_once("conn.php");
$id = $_POST['productid'];
$query = mysqli_query($conn,"SELECT productbrand FROM products WHERE productid = '$id' ");
while($rs = mysqli_fetch_array($query,MYSQLI_BOTH)) {
$brand = $rs['productbrand'];
}
echo $brand;
?>
Please add the data in json format and specify the datatype as json in ajax function
$.ajax({
url: "ff.php",
type: "POST",
data: {
productid : val
// more fields can be added here
},
dataType: 'json',
success: function(return){
// process success
},
error: function(err) {
// Process failure
}
});
I think the format of ajax data attribute is wrong . You should try this :
data:{productid:val}
UPDATE :
you should select both productid and product code in select statement
<td>
<select name="drpcode" onchange="getState(this.value)" class="form-control
name_list">
<?php $drp = mysqli_query($conn,"SELECT productid,productcode FROM
products");
while ($dp = mysqli_fetch_array($drp)) {
?><option value="<?php echo $dp['productid']; ?>"><?php echo
$dp['productcode']; ?></option><?php } ?>
</select>
</td>
function getState(val) {
$.ajax({
type: "POST",
url: "ff.php",
data:{productid:val},
success: function(data){
$("#brandss").val(data);
}
});
}
Try running the query before select and then display result with loop-
<?php $drp = mysqli_query($conn,"SELECT productcode FROM products"); ?>
<select name="drpcode" onchange="getState(this.value)" class="form-control name_list">
<?php while ($dp = mysqli_fetch_array($drp)) { ?>
<option value="<?php echo $dp['productid']; ?>"><?php echo $dp['productcode']; ?>
</option><?php } ?>
</select>

Ajax multiple dropdown return value- php mysql

i had 4 table like this
Table
And then im going to fill this form
Form
the workflow is, when i select Item Type and Treatment, the price should be filled based on the ServicePrice Table, I can get the Price from ServicePrice, but when I check XHR on network, it shows the value of Price but its data just show for 1st time, I mean when the modal opened, it shows the first data, when the option changed, the Price value keep like the 1st time modal open. so I want whenever the Item Type or Treatment changed, I want to make the price box filled dynamically
here's my form
<tr>
<td>Item Type</td>
<td>
<select name="ItemTypeID" class="form-control" id="ItemType" >
<option selected=""></option>
<?php
$sql2 = mysql_query("select * from itemtype");
while($record = mysql_fetch_array($sql2)){
?>
<option value="<?php echo $record['ID']; ?>" title="<?php echo $record['DefaultSpec']; ?>"> <?php echo $record["Name"]; ?> </option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Treatment</td>
<td>
<select name="TreatmentID" class="form-control" id="Treatment">
<?php
$sql2 = mysql_query("select * from treatment");
while($record = mysql_fetch_array($sql2)){
?>
<option value="<?php echo $record['ID']; ?>"> <?php echo $record["Name"]; ?> </option>
<?php } ?>
</select>
</td>
</tr>
and then my ajax
$("#ItemType, #Treatment").change(function(){
var ItemType = $(this).val();
var Treatment = $(this).val();
console.log(Treatment);
console.log(ItemType);
$.ajax({
type: "POST",
dataType: "html",
url: "GetPrice.php",
data: {ItemTypeID: ItemType, TreatmentID: Treatment},
success: function(result){
console.log(result);
$("#Price").val(result);
});
});
my GetPrice.php
<?php include "../Content/connection.php";
$a="SELECT * FROM ServicePrice WHERE ItemtypeID = '".$_POST["ItemTypeID"]."' AND TreatmentID = '".$_POST["TreatmentID"]."'";
$q=mysql_query($a);
while($record=mysql_fetch_array($q)){
echo $record['Price'];
}
?>
EDIT :
im making it like this it give me correct answer but the Price value triggered only if treatment dropdown changed, how can i make it trigger by booth dropdown?
$("#ItemType").change(function(){
var ItemType = $(this).val();
$("#Treatment").change(function(){
var Treatment = $(this).val();
the $(this).val() inside the change event handler will not work to get data for both the fields,
instead fetch the data of ItemType and Treatment individually
$("#ItemType, #Treatment").on('change', function(){
var ItemType = $("#ItemType").val();
var Treatment = $("#Treatment").val();
$.ajax({
type: "POST",
url: "GetPrice.php",
data: {ItemTypeID: ItemType, TreatmentID: Treatment},
success: function(result){
$("#Price").val(result);
}
});
});

POST the value of select option to another page PHP

I need to POST the value of the selected option to use in a query on another page.
This is my form:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="switch-area">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name'] ?>" value="<?php echo $test3['Name'] ?>"><?php echo $test3['Name'] ?></option>
<?php endwhile; ?>
</select>
<button class="btn btn-info">View Area</button>
</form>
I am using ajax and this is my code:
$(document).ready(function() {
$('select[name="switch-area"]').change(function(){
var status = $(this).val();
$.ajax({
type: 'POST',
url: 'sim-area.php',
data: {changeStatus: status}
});
});
});
Then on sim-area.php this is my code to grab the data:
$selectedArea = $_POST['switch-area'];
But I keep getting an undefined index error, am I posting this in the correct way?
You're sending changeStatus but not switch-area in your data, you want
$selectedArea = $_POST['changeStatus'];

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);
}
});
}

Autosave from php to mysql without page change or submit button

Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?
I am using php and mysql to create the system, but will happily use JavaScript if required
I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htm which is similar to what i want, however i need it to actually store that data in my database not temporary storage.
Any Guidance appreciated,
Ian
BIG EDIT
So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.
can i get it to work?
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id</td>
<td>
<select name="status" id="status">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
and on the page saveStatus.php:
<?php
if (isset($_POST['statusType'])) {
$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jobs", $con);
$st=$_POST['statusType'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
$resource = mysql_query($query)
or die (mysql_error());
}
?>
Where is the $id in saveStatus.php ?
You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.
For example:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).id;
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal, job_id: job_id },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id; ?></td>
<td>
<select name="status" id="<?php echo $job->job_id; ?>">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
*Note: .live() is deprecated, use .on() instead.
And saveStatus.php
$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
You will need to use JavaScript (+ jQuery for easier working) to achieve this.
Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.
Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajax method.

Categories