A form contains a dropdown menu on change it should fetch the value from the database using ajax and dislay the checkbox with .
uptil here its wking good,when i submit form the checkbox values is not getting posted.
<form name="test" >
<tr>
<td align="left"><b>System :</b> </td>
<td align="left">
<select name="system" size="1" onchange="regionsa(this.value);" >
<option value="0">Select a System</option>
<?php // Retrieve all the announcement types and add to the pull-down menu.
$q = "SELECT * FROM System";
$r = mysqli_query ($CARE_dbc, $q);
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
// $sys_name = $edit_menu['system'];
?>
<option value="<? echo $row[1];?>" <? if($row[1]==$edit_menu['system'])
{
echo $selec = "selected";
}?> >
<? echo $row[1];?>
</option>
<? }?>
</select>
</td>
</tr>
<tr>
<td align="left">
<b>User Type :</b> </td>
<td align="left" ><span id="sant">
<?php // Retrieve all the announcement types and add to the pull-down menu.
$qUTdd = "SELECT * FROM `UserType`";
$rUTdd = #mysqli_query ($CARE_dbc, $qUTdd);
while ($rUTddrow = mysqli_fetch_assoc($rUTdd))
{
$utype_qr = mysqli_query($CARE_dbc,"SELECT * FROM `menu_users` WHERE `menu_users`.menu_id='".$_REQUEST['id']."'");
//$ut = mysqli_fetch_assoc($utype_qr);
?>
<input type="checkbox" name="user_type[]" value="<? echo $rUTddrow['idUType'];?>" <? while($ut = mysqli_fetch_assoc($utype_qr))
{
if($ut['user_type']==$rUTddrow['idUType'])
{
echo "checked";
}
}?> /> <?echo "<b>".$rUTddrow['userType']."</b>"; ?>
<?
}
?>
</span>
</td>
</tr>
<input type="submit" name="submit" value="Add" />
<input type="hidden" name="submitted" value="TRUE" />
</form >
<script language="javascript">
var http = createRequestObject();
function createRequestObject()
{
var request_o; //declare the variable to hold the object.
var browser = navigator.appName; //find the browser name
if(browser == "Microsoft Internet Explorer"){
/* Create the object using MSIE's method */
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
/* Create the object using other browser's method */
request_o = new XMLHttpRequest();
}
return request_o; //return the object
}
function regionsa(stateid)
{
//alert(stateid);
http.open('get','internal_request.php?id='+stateid);
http.onreadystatechange = handleresponse;
http.send(null);
}
function handleresponse()
{
if(http.readyState == 4)
{
var response = http.responseText;
//alert(response);
document.getElementById('sant').innerHTML = response;
}
}
</script>
Internal_request.php
<?php
if($_REQUEST['id']=='annmet' && isset($_REQUEST['id']) && !empty($_REQUEST['id']))
{
$qUTdd = "SELECT * FROM annmet.`usertype`";
$rUTdd = #mysqli_query ($CARE_dbc, $qUTdd);
while ($rUTddrow = mysqli_fetch_assoc($rUTdd))
{
$utype_qr = mysqli_query($CARE_dbc,"SELECT * FROM CARE.`menu_users` WHERE CARE.`menu_users`.menu_id='".$_REQUEST['id']."'");
//$ut = mysqli_fetch_assoc($utype_qr);
?>
<input type="checkbox" name="user_type1[]" value="<? echo $rUTddrow['idUType'];?>"
<? while($ut = mysqli_fetch_assoc($utype_qr))
{
if($ut['user_type']==$rUTddrow['idUType'])
{
echo "checked";
}
}?> /> <?echo "<b>".$rUTddrow['UserT']."</b>"; ?>
<?
}
}
?>
name of the AJAX generated checkboxes is user_type*1*[] while original checkbox name is user_type[].
EDIT:
You have not mentioned a value for "method" attribute of Form element. Therefore this form uses default form submission method which is GET. Therefore you don't get any data for $_POST variable. Print $_GET variable using print_r and check.
Related
I am trying to insert single form value called multiple times using ajax call to mysql in php with submit all button . I have store all the forms data to localStorage. But when I am trying to insert all the values to mysql one form value is inserting and other form values is taking null value.
**loadquestions1.php**
<form method="post">
<table>
<tr>
<td>
<?php echo "<h5>Question: ".$question_no ."</h5><h5> ".$question_title ."</h5>"; ?>
</td>
</tr>
</table>
<div class="center">
<textarea placeholder="Write your answer here..." class="outer persisted-text" name="pt<?php echo $question_no; ?>" id="persisted-text" onchange="changeBack();" rows="10" cols="100"></textarea>
<span><input type="hidden" name="question_no<?php echo $question_no; ?>" value="<?php echo $question_no; ?>" /></span>
<span><input type="hidden" name="question_title<?php echo $question_no; ?>" value="<?php echo $question_title; ?>" /></span>
</div>
<button class="btn btn-success" name="save">Save</button>
<?php } ?>
</form>
function load_questions1(questionno)
{
document.getElementById("current_que").innerHTML=questionno;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText=="over")
{
window.location="result.php";
alert("hello");
}
else
{
document.getElementById("load_questions1").innerHTML=xmlhttp.responseText;
load_total_que();
var supported = '',
unsupported = 'Oh no! Your browser does not support localStorage.';
if (window.localStorage) {
$('.persisted-text').keyup(function () {
localStorage.setItem(this.name+questionno, this.value);
}).val(function () {
return localStorage.getItem(this.name+questionno) || supported
})
} else {
$('.persisted-text').val(unsupported);
}
}
}
};
xmlhttp.open("GET", "forajax/load_questions1.php?questionno="+ questionno, true);
xmlhttp.send(null);
}
**config.php**
if (isset($_POST['save'])) {
$size = sizeof($_POST);
$number = $size/3;
$query = "SELECT * FROM add_question where online_exam_title='$_SESSION[add_exam]'";
$data = mysqli_query($conn, $query);
$count=mysqli_num_rows($data);
for($i=1;$i<$count;$i++) {
$index1 = 'pt'.$i;
$pt[$i] = $_POST[$index1];
$index2 = 'question_no'.$i;
$question_no[$i] = $_POST[$index2];
$index3 = 'question_title'.$i;
$question_title[$i] = $_POST[$index3];
//$question_no = $_POST['question_no'];
$sql="INSERT INTO subjective_answer (placeholder, exam_type, username, question_no, question_title) VALUES ('$pt[$i]', '$_SESSION[add_exam]', '$_SESSION[username]', '$question_no[$i]', '$question_title[$i]')";
$result=mysqli_query($conn,$sql);
}
if($result)
{
echo "record inserted";
}
}
I need help on this code. I want to dynamically prohibit a user from adding to cart if the requested stock item (Database) is less than his request (qty). Will appreciate, if I can know where I am wrong and probably someone correct it for me.
HTML FORM
<form action="cart.php?adm_id=<?php echo urlencode($patient["adm_id"]);?>" method="post" name="CartForm" target="_self">
<p>Product Name:<select name="prod_name" size="1" id="prod_name">
<option value="Select">Select</option>
<?php
while ($line = mysqli_fetch_array($query, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['prod_name'];?>"> <?php echo $line['prod_name'];?> </option>
<?php } ?>
</select></p>
<p>Quantity:<input type="number" name="qty" id="qty" size="30" required="required"/></p>
<input name="submit" type="submit" value="Add to Cart" id="btn"/> | <input name="reset" type="reset" value="Cancel" />
Ajax Code:
<script src="javascript/jquery-2.0.3.js">
</script>
<script type="text/javascript">
$(document).ready(function(ex) {
//$('#stock').load('pharmacy_summary.php');
$('#qty').change(function(){
var prod_name = $('#prod_name').val();
var qty= $('#qty').val();
$.ajax({
url: 'confirmStock.php',
data:{prod_name: prod_name, qty: qty},
success: function(e){
if(e == 'true'){
/*if the quantity is greater than the stock*/
alert('stock Item is lower to your request, reduce it');
$('#btn').prop('disabled', true);
}else{
$('#btn').prop('disabled', false);
} }
})});
});
</script>
PHP/MYSQLI Code:(ConfirmStock.php)
<?php require_once("/includes/db_connection.php");?>
<?php require_once("/includes/functions.php");?>
<?php
if(isset($_GET['prod_name'])){
$getProd = $_GET['prod_name'];
$getQty = $_GET['units'];
global $connection;
$val = "SELECT * FROM pharmacy_stock_tab WHERE prod_name='".$getProd."'";
$conf = mysqli_query($connection,$val);
$fetchVal = mysqli_fetch_array($conf);
$stock = $fetchVal['units'];
if($getQty>$stock){
return $stock;
}else{
return $stock;
}
}
?>
You must change the way you send response and the way you handle the response. change the code in ConfirmStock.php
change the return statements in following way
$result = array();
if($getQty>$stock){
$result['success'] = 'true';
$result['stock'] = $stock;
}else{
$result['success'] = 'false';
}
header('Content-Type: application/json');
echo json_encode($result);
die();
In Ajax success method
success: function(response){
if(response.success == 'true'){
/*if the quantity is greater than the stock*/
alert('stock Item is lower to your request, reduce it');
$('#btn').prop('disabled', true);
}else{
$('#btn').prop('disabled', false);
} }
I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.
So far so good. What I'm trying to do is to close colorbox and refresh a div on success.
I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.
I'll appreciate any help here.
Here is my ajax:
jQuery(function(){
jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
cbox_submit();
}});
});
function cbox_submit()
{
jQuery("#pre-process").submit(function(){
jQuery.post(
jQuery(this).attr('action'),
jQuery(this).serialize(),
function(data){
jQuery().colorbox({html: data, onComplete: function(){
cbox_submit();
}});
}
);
return false;
});
}
form php code:
<?php
error_reporting(-1);
include "conf/config.php";
if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect
$session_id=session_id();
if(isset($_REQUEST['submit'])){
if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
}
if (array_search("", $_POST['opt']) !== false)
{
$msg = "Please select all accessories!";
}else{
$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));
if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}
$sql['session_id'] = $session_id;
$sql['rest_id'] = $_POST['rid'];
$sql['prod_id'] = $_POST['pid'];
$sql['extras'] = $extras;
$sql['added_date'] = Date("Y-m-d H:i:s");
$newId=insert_sql("cart",$sql);
}
}
?>
<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
<?php
$name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
$getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
while ($rsrw = #mysql_fetch_array($getRss)) {
$goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");
$goptionals=explode(', ',($goptionals));
echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
foreach($goptionals as $v)
{
$vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
while ($rsgb = #mysql_fetch_array($vname)) {
$aa=$rsgb['optional'];
}
echo "<option value=".$v." >".$aa."</option>";
}
echo "</select>(required)<br>";
//}
}
$getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid."");
?>
<br><br>
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td bgcolor="#EAFFEC">
<div style="width:440px; ">
<?php
while ($rssp = #mysql_fetch_array($getRss)) {
$optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
$price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>" /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>
</td>
</tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
</div><input type="hidden" name="submit" /><input id='submit' class="CSSButton" style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />
<br /><br />
</div>
</form>
I don't know colobox, but if I understand well what you are trying to do,
I would say your javascript should more look like this
function cbox_submit()
{
jQuery("#pre-process").submit(function(e) {
e.preventDefault(); // prevents the form to reload the page
jQuery.post(
jQuery(this).attr('action')
, jQuery(this).serialize()
, function(data) {
if (data['ok']) { // ok variable received in json
jQuery('#my_colorbox').colorbox.close(); // close the box
}
}
);
return false;
});
}
jQuery(function() {
jQuery('#my_colorbox').colorbox({
maxWidth: '75%'
, onComplete: cbox_submit // Bind the submit event when colorbox is loaded
});
});
You should separate at least your php script that does the post part.
And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:
<?php
# ... post part ...
# if success
ob_clean();
header('Content-type: application/json');
echo json_encode(array('ok' => true));
?>
i have few checkboxes named as HR,visitor,gaurd now i want to get which ever chckbox is selected according to it names of the employee belonging to that team whether HR or Guard or visitor to be shown in dropdown list
<select name=cmbname id="cmbname" width='50%'>
ALL
`
$objDB->SetQuery($sql);
$res = $objDB->GetQueryReference();
if(!$res)
exit("Error in SQL : $sql");
if($objDB->GetNumRows($res) > 0)
{
while($row = mysql_fetch_row($res))
{
print("
<option value='{$row[0]}'>{$row[0]}</option>");
}
}
mysql_free_result($res);
?>'
Himani ,
Try this. Hope it will be useful to you. Instead of text-area you can use drop-down.
Try this way gives you solution
<script type="text/javascript">
//javascript
function clicked_checkbox()
{
document.form.submit();
}
</script>
<?php
$hr = isset($_REQUEST['HR'])?$_REQUEST['HR']:false;
$guest = isset($_REQUEST['guest'])?$_REQUEST['guest']:false;
$visiter = isset($_REQUEST['visiter'])?$_REQUEST['visiter']:false;
//Prepare query with retrieved value and put value in Dropdown
$sql = 'select * from table ';
if($hr) { $sql .= "where user = '$hr'" };
if($guest) { $sql .= "where user = '$guest'" };
if($visiter) { $sql .= "where user = '$hr'" };
$objDB->SetQuery($sql);
$res = $objDB->GetQueryReference();
if(!$res)
exit("Error in SQL : $sql");
if($objDB->GetNumRows($res) > 0)
{
while($row = mysql_fetch_row($res))
{
print("<option value='{$row[0]}'>{$row[0]}</option>");
}
}
mysql_free_result($res);
?>
//on change of checkbox we'll call above function and set data to dropdown
<form name='form' method='get' action='#'>
<input type="checkbox" id="checkbox_HR" name="HR" value="true" <?php if($hr) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
<input type="checkbox" id="checkbox_guest" name="guest" value="true" <?php if($guest) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
<input type="checkbox" id="checkbox_user" name="visiter" value="true" <?php if($visiter) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
</form>
like this you can achieve :)
I have a table that prints out all available cameras. It uses a form to change these settings. The problem is that the form only updates the last camera in the entry. In other words if I change the form and hit "Apply" for the last camera in the list it will work. If I change the form for any other camera in this list it changes the one to have the same settings as the last camera in the list. There are no issues with any values as far as I can tell.
Sorry for the long dump here, but without being able to narrow down the problem I thought I should include the bulk of it:
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
$query_camera_name = "SELECT camera_id, camera_name, camera_status, camera_quality, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
if (isset($_POST['apply_changes'])) {
//process changes to camera options
$camera_id = $_POST['camera_id'];
$camera_status = check_input($_POST['camera_status']);
$camera_name = check_input($_POST['camera_name'], "You entered an empty camera name. Enter another name and apply changes.");
$camera_quality = check_input($_POST['camera_quality']);
$query_insert_camera = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'", `camera_name` ="'.$camera_name.'", `camera_quality` ="'.$camera_quality.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_insert_camera);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']);
}
echo "<html>";
echo "<head>";
<link href="dashboard/webcam_widget.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function oncameraSubmit(camera_id)
{
document.active_cameras.camera_id.value = camera_id;
return confirm('Apply changes?');
}
</script>
<?php
echo "</head>";
echo "<body>";
if (!isset($result_cameras))
{
//TODO
}
else
{
if ($num_rows == 0)
{
echo '<b><i><center>You currently have no cameras setup. Add a Camera below.</center></i></b>';
}
else
{
?>
<form name="active_cameras" action="<?php htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="hidden" name="camera_id" value="" />
<table id="webcam-table">
<thead>
<tr>
<th>Camera Type</th>
<th>Name</th>
<th>Quality</th>
<th>Status</th>
<th>Camera Actions</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_rows;$i++)
{
//camera_status
if ($result_cameras[$i]["camera_status"] == "ENABLED")
{
$enabled_option = "value='ENABLED' selected='selected'";
$disabled_option = "value='DISABLED'";
}
else
{
$enabled_option = "value='ENABLED'";
$disabled_option = "value='DISABLED' selected='selected'";
}
//camera_quality
if ($result_cameras[$i]["camera_quality"] == "HIGH")
{
$high_option = "value='HIGH' selected='selected'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MEDIUM")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM' selected='selected'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MOBILE")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE' selected='selected'";
}
else
{
//TODO proper logging
}
//camera_type
if ($result_cameras[$i]["camera_type"] == "WEBCAM")
{
$webcam = "value='WEBCAM' selected='selected'";
$axis = "value='AXIS'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "AXIS")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS' selected='selected'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "IPCAM")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS'";
$other = "value='IPCAM' selected='selected'";
}
else
{
//TODO
}
?>
<tr>
<td>
<select name="camera_type">
<option <?php echo $webcam; ?>>Webcam</option>
<option <?php echo $axis; ?>>AXIS</option>
<option <?php echo $other; ?>>Other</option>
</select>
</td>
<td>
<input type="text" size="32" maxlength="64" name="camera_name" value="<?php echo $result_cameras[$i]["camera_name"]; ?>" />
</td>
<td>
<select name="camera_quality">
<option <?php echo $high_option; ?>>High</option>
<option <?php echo $medium_option; ?>>Medium</option>
<option <?php echo $mobile_option; ?>>Mobile</option>
</select>
</td>
<td>
<select name="camera_status">
<option <?php echo $enabled_option; ?>>Enabled</option>
<option <?php echo $disabled_option; ?>>Disabled</option>
</select>
</td>
<td>
<input type="submit" name="apply_changes" value="Apply" onClick="javascript:return oncameraSubmit(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/>
</td>
</tr>
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
}
}
It looks like you have multiple HTML elements with the same name. As such, you want to get back an array of values when the form is posted.
As such, Get $_POST from multiple checkboxes looks like it might be helpful.
Alternatively, extend oncameraSubmit so that it stores all the data in a hidden input field (not just the id). Then when you update the database, use these hidden fields.
Your form element names are clashing. When you define a form element e.g. 'camera_status' twice, you will only receive the last value in the POST.
Use form array notation, e.g.: "camera_status[]" or even better "camera_status[$id]". Then your PHP code will recieve arrays as POST data and you will be able to update everything at once.