Change text box value after deleting phpgrid row - javascript

I need to refresh the Sub Total div/text box value after deleting the row of phpgrid (phpgrid.org).
Before Delete:
After deleting the second row:
<div id="sub_total_div">
<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];
?>"/>
</div>
Please help me.
Edited code:
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();
//refresh/update the sub total value when adding
$("#sub_total_div").load(location.href + " #sub_total_div");
}
});
}
}

Create a new php file:
Gettotal.php
$sql=mysqli_query($connection,'select sum(amount) from sales_temp');
$row = mysqli_fetch_array($sql);
echo $row[0];
your js code will be:
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}]);
//Ajax call to get the sub
$("#sub_total_div").load("gettotal.php");
}
});
}
}
Note : This is not proper method to go with but in your case this will work

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

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

Related

Laravel checkbox data only saves true or false to the DB

My Ajax call passes checkbox value to the controller without problems. I have passed as true or false and tried as 1 or 0 values. But when I try to save the data to DB I am only able to save true/1. If I modify the code I can save false/0.
EXAMPLE: if I do click the checkbox and save true value for example. That is saved to DB, but whenever I unclick the checkbox the false value is not saved to DB.
Hope someone can help me to understand what is the problem. I try to include as much of my code as possible.
function privacyFunction(id) {
var checkBox = id;
var checkboxName = id.name;
var checkboxData = id.checked; //? 1 : 0
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: BASE_URL+'/settings/privacy/save',
type: "POST",
data: {'checkboxName':checkboxName, checkboxData:'checkboxData'},
success: function(response) {
console.log(checkboxName, checkboxData);
},
});
}
public function save(Request $request){
$user = Auth::user();
$checkboxName = $request->checkboxName;
$checkboxData = $request->checkboxData;
if($checkboxData == true){
$data = 1;
} else {
$data = 0;
}
if($checkboxName === 'private_profile'){
$update = DB::table('users')
->where('user', $user->id)
->update([$checkboxName => $data]);
}
}
<input type="checkbox" name="private_profile" id="private_profile" value="1" #if($details['private_profile'] == 1) {{ 'checked' }} #endif onclick="privacyFunction(this);">

Check any data after confirmation message using JSON

I want to make the data alert successfully saved or fail after the user selects on the confirmation message. In this case data checking occurs after the user confirms the message I made.
This is my Javascript Code :
$('#add-btn').on('click', function(event){
var confirmation = confirm("Do you want to save ?");
if (confirmation == true) {
var code = $('#code').val();
var name = $('#name').val();
var unit = $('#unit').val();
var price_code = $('#price_code').val();
var type = $('#type').val();
var final = $('#final').val();
var dataString = 'code=' +code+ '&unit=' +unit+ '&price_code=' +price_code+ '&type=' +type;
if (code != '' && name != '' && unit != '' && price_code != '' && type != '' && final != ''){
event.preventDefault();
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.status == 'success'){
alert("Success !");
}
else if(data.status == 'error'){
alert("Data already used !");
}
}
});
}
else{
alert('Please fill all fields !');
}
}
});
All input success to save but the alert cannot show.
I think problem in your php file. your JOSN data is not in correct format that you received in success.Please try this in your add_data.php file
//All code goes here and after insert try this
$array = array();
if(if data insert successfully) {
$array['status '] = 'success';
} else {
$array['status '] = 'error';
}
header('Content-Type: application/json');
echo json_encode($array);
The success function is only executed if everything went well. If there has been any error, you need to add the Ajax failure function as follows:
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
alert("Success !");
}
}).fail(function () {
alert("Data already used !");
});
finally I find my solution. I'm sorry for my carelessness.
That happened because my variable dataString did not complete.
It should be :
var dataString = 'code=' +code+ '&name=' +name+ '&unit=' +unit+
'&price_code=' +price_code+ '&type=' +type+ '&final=' +final;
Thank you all for your kindness :-)

page redirect is not working in jquery

<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.

Make a submit button POST and AJAX call same time?

I have this form that will POST to show_aht2.php but I also want it to make the AJAX call that you see in my code below. So, how can I do both so the user doesn't go to the other? I want the user to stay on map.php
thanks in advance
map.php
<form action="show_aht2.php" method="post">
<input type="radio" name="date_selected" value="1d" checked="checked"/>1d
<input type="radio" name="date_selected" value="1w" />1w
<input type="radio" name="date_selected" value="1m" />1m
<input type="radio" name="date_selected" value="3m" />3m
<input type="submit" id="aht_btn" name="get_aht" value="Get AHT" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(){
$.ajax({
type:"GET",
url : "show_aht2.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//doing stuff
//get the MIN value from the array
var min = data.reduce(function(prev, curr) {
return isNaN(+curr['aht_value']) || prev < +curr['aht_value'] ? prev : +curr['aht_value'];
}, 1000000);
// alert("min:" + min); //return min for debug
//get the MAX value from the array
var max = data.reduce(function(prev, curr) {
return isNaN(+curr['aht_value']) || prev > +curr['aht_value'] ? prev : +curr['aht_value'];
}, -1000000);
//alert("max:" + max); //return max number for debug
//function for calculation of background color depending on aht_value
function conv(x){
return Math.floor((x - min) / (max - min) * 255);
}
//function for background color
//if NA then show white background, either show from green to red
function colorMe(v){
return v == 'NA' ? "#FFF" : "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
}
//going through all DIVs only once with this loop
for(var i = 0; i < data.length; i++) { // loop over results
var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
if(divForResult.length) { // if a div was found
divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
// alert("station " + data[i]['station'] + " <br>aht value" + data[i]['aht_value'] + "<br>timestamp:"+data[i]['ts_generated']);
}//end if
}//end for
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht2.php
if (isset($_POST['get_aht'])) {
if($_POST['date_selected'] == "1d" )//yesterdays result and using past 10 minute
{
$start_date = $one_day;
//$interval_value = "10 MINUTE";
//echo $start_date;
}
elseif($_POST['date_selected'] == "1w" )//1 week results
{
$start_date = $one_week;
//$interval_value = "7 DAY";
//echo $start_date;
}
elseif($_POST['date_selected'] == "1m" )//1 month results
{
$start_date = $one_month;
//$interval_value = "30 DAY";
//echo $start_date;
}
elseif($_POST['date_selected'] == "3m" )//3 month results
{
$start_date = $three_month;
//$interval_value = "90 DAY";
//echo $start_date;
}
}
/* what I expect from ther call back*/
$result = array();
foreach ($memo as $username => $memodata) {
if (in_array($username, array_keys($user))) {
// Match username against the keys of $user (the usernames)
$userdata = $user[$username];
//if AHT is null give N/A as value
if (is_null($memodata['aht_value'])) {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => 'NA',
'station' => $userdata['station']//,
// "ts_generated" => $userdata['ts_generated']
);
}//end inner if
//else give the actual value of AHT without the decimals
else {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => substr($memodata['aht_value'],0,-3),
'station' => $userdata['station']//,
// "ts_generated" => $userdata['ts_generated']
);
}//end else
}//end outer if
}//end for
echo json_encode($result);
do ajax call first, then submit form with .submit() later with callback of ajax.
<form action="show_aht2.php" method="post" id="formtopost">
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function() {
$.ajax({
type: "GET",
url: "show_aht2.php",
data: {}, // do I need to pass data if im GET ting?
dataType: 'json',
success: function(data) {
//doing stuff
//end success
},
always: function() {
//submit form !!!
$("#formtopost").submit();
}
}); //end ajax
}); //end click
}); //end rdy
</script>
Try :
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(event){
event.preventDefault();
$.ajax({
type:"GET",
url : "show_aht2.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//doing stuff
}//end success
});//end ajax
});//end click
});//end rdy
</script>
Use method preventDefault : http://api.jquery.com/event.preventdefault/
You could submit the form with ajax rather than trying to do both at the same time
Something like this maybe?
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(){
// This prevents the form from submitting
event.preventDefault();
// Capture form input
var $form = $(this);
var serializedData = $form.serialize();
// Run the ajax post
$.ajax({
url : "show_aht2.php",
type:"POST",
data: serializedData
success: function(response) {
// Do something
}
});
});//end click
});//end rdy
</script>

javascript alert in an if else statement not triggering

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});
I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

Categories

Resources