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.
Related
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"
}
});
});
Actually I am developing one website where i want to assign orders to delivery staff and area or bakers from where he will pick up the delivery material.
Above picture shows area name and bakers from where delivery staff will pickup the delivery material. So for each order (row) i want to create 2 List Boxes and depending on selection of 1st listbox i want to change the content of 2nd listbox.
<select name="<?phpecho $CurrentOrders->comment_ID; ?>" id="courseid" style="width:100%;">
<option value="">-----Select Pick Up Area----</option>
<?php
$Area = DB::table('area')
->get();
foreach ($Area as $Area) {
?>
<option id="<?php echo $Area->area_id; ?>" value="<?php echo $Area->area_name; ?>"><?php $Area->area_name; ?></option>
<?php } ?>
</select>
</td>
Above code is to create dynamically listboxes.
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#1").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
//alert(dataString);
$.ajax({
type: "POST",
url: "ajax_section.php",
//data: dataString,
data: {'id': id},
success: function (html){
$("#sectionid").html(html);
},
error: function () {
alert('Error');
}
});
});
});
</script>
Above script is to create the content of 2nd listboc based on selection of 1st listbox.
<?php
if($_POST['id']) {
$id=$_POST['id'];
$sql=DB::table('vendors')
->where('vendors_area','=',$id)
->get();
$count=0;
foreach($sql as $sql) {
$count++;
}
if ($count > 0) {
echo "<option selected='selected'>---- Select Section Name ---- </option>";
foreach($sql as $sql) {
$id=$sql->vendors_id;
$data=$sql->vendors_name;
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
}
?>
And above code is to create and show the content of 2nd listbox based on selection of 1st.
But all this codes are working for only 1 listbox. It is not working dynamically Even if have changed written scripts for all listboxws as i written for 1st listbox(as #1).
please help me out.
You need to change
$("#1").change(function ()
to
$(document).on('change',"#1",function()
in your javascript code
I have a table with multiple rows that lists records from my database.
These records are projects' information and in each row, I have drop down list to modify the status of the project.
To do so, I used Ajax because I hate to refresh the whole page after update.
This is the function I created to do the update:
function call(){
var projid=$('#projid').val();
var projstatus=$('#projstatus').val();
var dataall={'projid':projid, 'projstatus':projstatus};
$.ajax({
type: 'POST',
url: "stsproj.php",
data: dataall,
success: function (data) {
}
});
}
And below is my drop down list:
<?php do { ?>
<td>
<form action="<?php echo $editFormAction; ?>" method="post" name="form2" id="form2">
<input type="hidden" name="MM_update" value="form2" />
<input type="hidden" name="projid" id="projid" value="<?php echo $row_projlist['projid']; ?>" />
<select name="projstatus" id="projstatus" class="select1" onchange="call()">
<option value="<?php echo $row_status['projstatus'];?>"><?php echo $row_status['sts'];?></option>
<option value="1">Awaiting</option>
<option value="2">Ongoing</option>
<option value="3">Finishing</option>
</select>
</form>
</td>
<?php }while($row_projlist = $projlist->fetch(PDO::FETCH_ASSOC)); ?>
My problem is the following:
When I update the status of the first project, it works but when I try to do it with other projects, it doesn't work.
To be more specific, the parameters of the first project are sent always (this is what firebug says).
Please help!
Your problem is due to duplicate ids. You don't need to use ids(actually do not use id for automatic list generation. Id names must be unique). Remove call function from your select box and use below javascript;
You can use such js to handle that;
$(function() {
$("select[name='projstatus']").change(function() {
var projid = $(this).parent("form").find("input[name='projid']").val();
var projstatus = $(this).val();
var dataall = {'projid':projid, 'projstatus':projstatus};
$.ajax({
type: 'POST',
url: "stsproj.php",
data: dataall,
success: function (data) {
}
});
});
});
You can see working example for form manipulating part here : http://jsfiddle.net/cubuzoa/SYf8s/
The previous answer will probably solve your problem, but I think it can be simplified.
for the form...
<form>
<select class="select1" onchange="call(<?=$row_projlist['projid']?>)">
<option value="<?=$row_status['projstatus']?>"><?=$row_status['sts']?></option>
<option value="1">Awaiting</option>
<option value="2">Ongoing</option>
<option value="3">Finishing</option>
</select>
</form>
and the javascript
function call(id)
{
$.post('stsproj.php',{'projid':id, 'projstatus':$('#projstatus').val()} )
.done(function(data){
//do something with data
});
}
on my web page i have text area like this
and i suppose to get data in textarea when i alternate the value of select box( or onChange event), so i used ajax function
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#mybox").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
and this is my select box code,
<select name="txtname" id="txtname" onChange="myCall()" >
<option value="0">Select Age:</option>
<option value="100083">100083</option>
<option value="22-26">22-26</option>
<option value="26-30">26-30</option>
<option value="30-34">30-34</option>
</select>
actualy i want to fetch record on the basis of select box value, this function working fine for static value but i am puzzled how to get data from data base..
and my ajax page coding is here..
<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("hmc", $con);
$sql="SELECT * FROM news WHERE name = '22-26'";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<?php echo $row['news1'];?></h3></td>
</tr><br /><hr /><br />
<?php
}
?>
</div>
any idea will be appreciated...
Your ajax call is not proper, you need to pass your select box value to the php side, like this
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "html",
data:"value="+$("#txtname").val();
});
then use this value on php side using $_GET['value']
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.