Updating database values using ajax request - javascript

I have a form and it has radio buttons that a user must click to increement a value in the database but I click the radio button and nothing happens in the database heres my form code:
<form id="myform" name="myform" method="post">
<div class="radio show-options">
<li><label id="l_security"><input type="radio" id="r_security" name="weekend" value="security" />Security</label> (<label id="c_security">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_manager"><input type="radio" id="r_manager" name="weekend" value="manager" />Manager</label> (<label id="c_manager">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_cleaner"><input type="radio" id="r_cleaner" name="weekend" value="cleaner" />Cleaner</label> (<label id="c_cleaner">0</label>)</li>
</div>
</form>
here the script for the form
<script type="text/javascript">
var lastClicked = '';
function getTotals() {
// function to get click counts as JSON from helper page
// expects get_count.php to be in same directory level
$.ajax({
type: "GET",
url: "get_count.php",
dataType: "json",
error: function(xhr, status, msg) {
alert("Failed to get click counts: " + msg);
}
})
.done(function(data) {
// loop through JSON variables, assign to count labels
$.each(data, function(key, value) {
var tmp = "#c_" + key;
$(tmp).text(value);
});
});
}
function processClick(obj) {
// function to increment click count via ajax
// expects increment_count.php to be in same directory level
if(lastClicked != obj.val()) { // don't count clicks on currently active radio button
lastClicked = obj.val(); // set currently clicked radio button to this one
var qs = "weekend=" + obj.val(); // set query string value
$.ajax({
type: "GET",
url: "increment_count.php",
data: qs,
error: function(xhr, status, msg) {
alert("Failed to process click count: " + msg);
}
})
.done(function() {
getTotals(); // update totals on successful processing
});
}
}
$(document).ready(function() {
getTotals(); // get click totals on initial page load
$(document).ready(function() {
// add click incrementing event handler to all radio buttons on page
$('input:radio').click(function() {
processClick($(this));
});
});
});
</script>
here is get_count.php
<?php
require('db_connect.php');
// get new count totals, pass as JSON
$rs = mysql_query("SELECT * FROM employee") or die('Cannot get updated click counts');
if(mysql_num_rows($rs) > 0) {
$out = "{ ";
while($row = mysql_fetch_array($rs)) {
$out .= "\"$row[name]\" : $row[leave], ";
}
$out = substr($out, 0, strlen($out) - 2);
$out .= " }";
header("Content-type: application/json");
echo $out;
}
and here is increment_count.php
<?php
require('db_connect.php');
// if this is a postback ...
if(isset($_GET['weekend'])) {
// create array of acceptable values
$ok = array('security', 'manager', 'cleaner');
// if we have an acceptable value for position_name ...
if(in_array($_GET['weekend'], $ok)) {
// update the counter for that position
$q = mysql_query("UPDATE employee SET leave = leave + 3 WHERE name = '".$_GET['weekend'] . "'") or die ("Error updating count for " . $_GET['weekend']);
}
}
the leave value in the employee table is not increased

Related

Depending Dropdown from Multi Select Codeigniter

I have Customer Textfield, that contains customer Name. And then, i also have Project Textfield contains project name from customer. I want to make depending dropdown from multi select customer.
For example, user select : btel, celc, from the Customer Textfield, it just appear in Project Text field from btel and celc.
This is my JS:
<script type="text/javascript">
$('.filter_user_customer').select2();
$(document).ready(function(){
$('input[name="daterange"]').daterangepicker({
opens: 'left',
drops: 'up'
}, function(start, end, label) {
console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
});
// key category select box
var $category = $('select#categoryField');
// customer select box
var $customer = $('select#customerField');
// project select box
var $projects = $('select#projectField');
// on change user role, get projects
var $role = $('select#roleField');
// on change user id, get projects
var $userid = $('select#useridField');
// on change combiner
var $combiner = $('combinerField');
$customer.on('change', function () {
// get selected customer name
var customer = $(this).find('option:selected').val();
console.log(customer);
// post data with CSRF token
var data = {
action:'project',
customer: customer,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
// AjaxPOST to get projects
$.post('<?php echo base_url(); ?>Dashboard/perfomance_monitoring', data, function(json) {
projects_data = '<option value="0">All</option>';
$.each(json, function(index, obj){
projects_data += '<option value="'+obj.project_id+'">'+obj.project_id+'</option>';
});
// append all projects in project dropdown
$projects.html(projects_data);
}, 'JSON');
});
// on change user role, get project
$projects.on('change', function () {
// get selected project name
var project = $(this).find('option:selected').val();
// AjaxPOSt wit CSRF
var data = {
action:'role',
project: project,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
$.post('<?php echo base_url(); ?>Dashboard/perfomance_monitoring', data, function(json) {
role_data = '<option value="0">All</option>';
$.each(json, function(index, obj){
role_data += '<option value="'+obj.user_owner+'">'+obj.user_owner+'</option>';
});
// append all role data in Role dropdown
$role.html(role_data);
}, 'JSON');
});
// on change user ID, get project
$projects.on('change', function () {
// get selected project name
var project = $(this).find('option:selected').val();
// AjaxPOSt wit CSRF
var data = {
action:'userid',
project: project,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
$.post('<?php echo base_url(); ?>Dashboard/perfomance_monitoring', data, function(json) {
userid_data = '<option value="0">All</option>';
$.each(json, function(index, obj){
userid_data += '<option value="'+obj.user_id+'">'+obj.user_id+'</option>';
});
// append all role data in Role dropdown
$userid.html(userid_data);
}, 'JSON');
});
});
</script>
This is my Controller:
$array_data = array();
// only on Ajax Request
if ($this->input->is_ajax_request()) {
// if request for projects
if ($this->input->post('action') && $this->input->post('action') == 'project') {
// get customer name
$customer = $this->input->post('customer', true);
// get project data by customer name
$array_data = $this->ixt_models->fetch_project(trim($customer), 'project');
// AjaxPOST JSON response
echo json_encode($array_data);die();
}
This is my Model:
public function fetch_project($where_data = null, $type = null)
{
$query = '';
// customer only
if (is_null($type) && is_null($where_data)) {
// desire column from table
$this->db->select('cust_id');
// only unique customer
$this->db->distinct('cust_id');
// mysql table
$query = $this->db->get($this->table_helper);
}
// projects by customer
elseif ($type == 'project' && !is_null($where_data)) {
// desire column from table
$this->db->select('project_id');
// where clause
$this->db->where('cust_id', $where_data);
// mysql table
$query = $this->db->get($this->table_helper);
}
Right now, Project Textfield only show one choice when Customer take more than one selection :
Click here
You can try this code.
JavaScript code:
function onchangeFunctionName(id) {
if (id == '') {
$('#SelectedId').prop('disable', true);
} else {
$('#SelectedId').prop('disable', false);
$.ajax({
url: base_url + '/Url here get value by selected value',
type: "GET",
data: {'id': id},
dataType: 'json',
async: false,
success: function(data) {
$.each(data, function(key, value) {
$('#IdNameWhereShowValue').append('<option ' ' value="' + value.valueId + '">' + value.ValueName + '</option>');
});
},
error: function() {
}
});
}
}
Controller code:
$array_data = $this->ModelName->MethodName(PassIdhere passed by the js code);
echo json_encode(array_data);

Update status when checkbox clicked in PHP

I have a table create from datatables, how to change the status field when checkbox clicked, default status is 'before' then when checkbox clicked it update to be 'after'(in database field status), then the table reload..
This dataabs for display table
.....
foreach ($data as $key) {
// add new button, checkbox
$data[$i]['ceklolos'] = '<input type="checkbox" id_data="'.$data[$i] ['status_lolos'].'" class="btn btn-primary btnedit" >';
$i++;
...
How the rest of code, when checkbox in each data clicked that data row update from 'before status' (default database) to be 'after status', after that the table reload..
Thank you, Im using datatable and php
First, add custom data attribute to your checkboxes
<input type="checkbox" data-id="'.$data['id'].'" data-status="'.$data['status'].'" ../>
In your javascript,
// IIFE (Immediately Invoke Function Expressions)
(function (myapp){
myapp(window.jQuery, window, document);
}(function myapp($, window, document){
// $ is now locally scoped
$(function (){
// dom is now ready
var dtTable = $("#sometable").DataTable();
// dom events
$(document).on("change", '.btnedit', function (){
var $this = $(this);
var id = $this.attr("data-id");
var status = $this.attr("data-status");
// send ajax request
$.ajax({
url: 'path-to-your-php-file',
type: 'post',
dataType: 'json',
data: {
id: id,
status: status
},
beforeSend: function (){
// do something here before sending ajax
},
success: function (data){
// do something here
if( data.success ){
// update your table, or any html dom you want here
// if you want to add/remove rows from your dataTable,
// you can refer here
// https://datatables.net/reference/api/row.add()
// https://datatables.net/reference/api/row().remove()
//
}
},
error: function (data){
// do something here if error
// console.warn(data);
}
});
});
});
// The rest of the code goes here
}));
In your PHP file,
<?php
$id = $_POST['id'];
$status = $_POST['status'];
// do your update codes here
//
// after successful update return something so in your ajax you
// will know what happened behind the scene
$response = array('success' => false, 'msg' => 'Some error message');
if( some_update_function_success() ){
$response = array('success' => true, 'msg' => 'Some success message');
}
echo json_encode($response);

Textbox not clears when clicks the submit button

I am trying to clear the txtSubTotal text box after clicking the PROCEED button. It's not working though I tried some code examples, even in SO.
btnProceed/HTML
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="clearSubTotal();"/>
clearSubTotal()/JS
function clearSubTotal() {
$('#txtSubTotal').val('');
}
txtSubTotal
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php
$sql=mysqli_query($connection,"select sum(amount) from sales_temp");
$row = mysqli_fetch_array($sql);
echo $row[0];
?>"/>
form/HTML
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
Appreciate your help on this.
NOTE: Found that on the second button press, the text box clears. How to set this correctly for the first button perss?
ADD button/JS
function submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
window.location.reload();
}
});
}
}
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
ADD button/HTML
<td width="46"><button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
sales_functions.php
<?php
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include ("/../../pages/sales.php");
include("/../../dbutil.php");
if(isset($_POST['listCustomer'])){ $customer = $_POST['listCustomer'];}
if(isset($_POST['staff'])){ $user = $_POST['staff']; }
if(isset($_POST['btnProceed'])){
$result=mysqli_query($connection,
"INSERT INTO sales(cus_id,item_id,stock_id,receipt_no,qty,unit_price,amount,user_id,purchase_id)
SELECT C.cus_id, I.item_id, S.stock_id, $receipt_no, ST.qty, ST.unit_price, ST.amount, U.id, P.purchase_id
FROM customers C, items I, stock S, sales_temp ST, users U, purchase_items P
WHERE ST.staff='$user'
AND C.customer_name='$customer'
AND I.item_name=ST.item_name
AND S.stock_code=ST.stock_code
AND ST.purchase_id=P.purchase_id");
//Update available qty from purchase_items relevant only to the logged in user(sales_temp table may have records from multiple users)
$resultUpdate=mysqli_query($connection, "UPDATE purchase_items P INNER JOIN sales_temp ST ON (P.purchase_id = ST.purchase_id) SET P.avail_qty = (P.avail_qty - ST.qty) WHERE ST.staff='$user'");
//Delete records relevant only to current user. Here 'WHERE' clause use to prevent deleting other user's records.
$resultDelete=mysqli_query($connection, "DELETE FROM sales_temp WHERE staff='$user'");
if (!$result) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
// use exec() because no results are returned
if ($result) {
}
else
{
echo '<script type="text/javascript">',
'salesAddFail();',
'</script>';
}}
?>
After clicking on the submit button, the form is being submitted and your custom function is not being executed.
Delete the onclick from your input element and edit your jQuery code:
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
You can try it in your browser: https://jsfiddle.net/hy7jwg8m/1/
It is working perfect for me. And after clicking on submit it might be working for you but with the same time page will be redirected to new action
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);

PHP INSERT Prepared statement not inserting with ajax

I am attempting to create an INSERT statement using ajax and the query in a prepared statement form. I have never used AJAX with PDO before, so please excuse any ignorance.
The way this sits, I get the alert(data); error, but the alert pop-up just says "error | ". Is this referring to the javascript being incorrect or the php file? I believe it is the javascript because I am not even getting the php file to show up within my console network tab.
What is wrong within my AJAX?
<form method="POST" id="pdo-add">
<input name="first" id="pdo-add-first" placeholder="First Name">
<input name="last" id="pdo-add-last" placeholder="Last Name">
<input name="product" id="pdo-add-product" placeholder="Product">
<input name="add" type="submit" value="Add">
</form>
AJAX
$(function() {
$("#pdo-add").on("submit", function (event) {
event.preventDefault();
var add_first = $("#pdo-add-first").val();
var add_last = $("#pdo-add-last").val();
var add_product = $("#pdo-add-product").val();
$.ajax({
url: "pdoAddSend.php",
type: "POST",
data: {
"add_first": add_first,
"add_last": add_last,
"add_product": add_product
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert product record!");
alert(data);
} else {
//$("#newsletter-form")[0].reset();
$('.announcement_success').html('Product Successfully Added!');
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP
ini_set('display_errors', 1);
error_reporting(E_ALL);
$add_first = $_POST['add_first'];
$add_last = $_POST['add_last'];
$add_product = $_POST['add_product'];
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
echo $e->getMessage();
}
//if(isset($_POST['add'])) {
if(isset($add_first && $add_last && $add_product) {
$stmt = $dbc->prepare("INSERT INTO users (first, last, product) VALUES (:first,:last,:product)");
$stmt->bindParam(':first', $add_first);
$stmt->bindParam(':last', $add_last);
$stmt->bindParam(':product', $add_product);
$stmt->execute();
}
Use if (!empty($add_first) && !empty($add_last) && !empty($add_product)) { to check empty values
Use dataType json to return array from database
Insert Input dynamically in success of ajax
JS
$.ajax({
url: "pdoAddSend.php",
type: "POST",
data: {
"add_first": add_first,
"add_last": add_last,
"add_product": add_product
},
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
tr.append("<td><input name='id' value=" + data[i].id + " readonly=''></td><td><input name='first' value=" + data[i].first + "></td><td><input name='last' value=" + data[i].last + "></td><td><input name='product' value=" + data[i].product + "></td><td><input name='save' type='submit' value='Save'></td><td><input name='delete' type='submit' value='Delete'></td>");
$("#tableid").append(tr);
}
console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert product record!");
alert(data);
} else {
//$("#newsletter-form")[0].reset();
$('.announcement_success').html('Product Successfully Added!');
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
You'd better test these variables first, so that there is no "Undefined index" Notice occured.
And because you don't have a POST variable called add, if(isset($_POST['add'])) always be FALSE.
code here:
if(isset($_POST['add_product']) && isset($_POST['add_last']) && isset($_POST['add_product'])) {
$add_first = $_POST['add_first'];
$add_last = $_POST['add_last'];
$add_product = $_POST['add_product'];
//then your db execute code here
}

Button to go through array one value at a time without page refresh

I have a function that generates 10 random and unique numbers between 1-20.
function contain($prevItems, $number) {
for ($k=0; $k<sizeof($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,20);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,10);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,20);
}
$prevItems[$i] = $num[$i];
}
sort($num);
I then have a button that fetches the first number from the array and echoes a text from database based on the number.
<form action="koe.php" method="POST">
<input id="myform" type="submit" class="btn btn-primary" name="submit" value="new question">
</form
if(isset($_POST['submit'])) {
if($result = $my->query("SELECT * FROM questions ORDER BY OID DESC LIMIT 1")) {
if($result = $my->query('SELECT * FROM questions WHERE OID="'.$prevItems[0].'"')) {
while($t = $result->fetch_object()) {
echo '<h2>'.$t->text.'</h2>';
}
}
}
}
My problem is this: I want the button to echo the next value from the previously. Like I want to echo prevItems[1] and then prevItems[2] without the page refresh because at the moment every time I press the button, the page refreshes and the function makes new 10 numbers so they're not unique anymore.
I've tried to stop page refresh with javascript
var frm = $('#myform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
I figured it can't work like this though but I'm not sure how to fix it.
To clarify: My problem is to go through array on a button click without page refresh. Everytime a button is pressed, the next number from array would show up. array[0] -> array[1] -> array[2] -> array[3]
I would change your php page to expect a post variable "num"
if(isset($_POST['num'])) {
if($result = $my->query("SELECT * FROM questions ORDER BY OID DESC LIMIT 1")) {
if($result = $my->query('SELECT * FROM questions WHERE OID="'.$_POST['num'].'"')) {
while($t = $result->fetch_object()) {
echo '<h2>'.$t->text.'</h2>';
}
}
}
}
//you probably want to google "mysql prevent injection" right after you get this working
Then in your ajax call you can pass in the "num"
$(function(){
$("mybutton").on("click", function() {
$.ajax({
type: "POST",
url: "myURL",
data: { num:myNums[0] },
success: function (data) {
$("#output").innerHTML += data;
myNums.splice(0,1); //take out the first num
}
});
});
});

Categories