Javascript object structure - javascript

I have a form collecting employee production data, the following is the code:
$(document).on('click','input#Apply.btn.btn-success',function(e){
var TableData;
TableData = storeTblValues();
var TableData1 = [];
$.each(TableData,function(index,value){
if(value.quantity && value.quantity >0 && value.quantity < 65535){
TableData1[index]={
"employee_id" : value.employee_id
, "operation_id" : value.operation_id
, "quantity" : value.quantity
}
}
});
// retrieving employee_id to fetch date data from date input
$.each(TableData1,function(index,value){
employee_idj = value.employee_id;
});
$('#cboxClose').click();
var datee = dateConvToMySqlDate($('input#dateOfProduction_'+employee_idj+'.dateOfProduction_.hasDatepicker').val());
if(!datee){alert(dateMessager);e.preventPropagation();return false;}
var noOfRecords = TableData1.length;
for(i=0;i<noOfRecords;i++)
{TableData1[i]['production_date'] = datee;}
var TableData1 = $.toJSON(TableData1);
alert(JSON.stringify(TableData1));
var qurl = '<?php echo base_url();?>production_entry/submitData';
$.ajax({
url: qurl,
type: "POST",
data:"pTableData=" + TableData1,
success: function(data){
var data = $.parseJSON(data);
if(data.status == 'error')
{
alert(data.errorMessage);
}else{
alert(noOfRecords+' records sent and '+' '+data.successMessage);
$('#tr_'+employee_idj).fadeOut();
}
}
});
function storeTblValues()
{
var TableData = new Array();
$('#searchOperationTable tr').each(function(row, tr){
var x = parseInt($(tr).find("input.quantity").val());
if(x){
TableData[row]={
"employee_id" : parseInt($(tr).find("input.hiddenemployeeId").val())
, "operation_id" : parseInt($(tr).find('td:eq(0)').text())
, "quantity" : parseInt($(tr).find("input.quantity").val())
}
}
});
TableData.shift();
return TableData;
}
});
When someone enter a quantity value equal to 0 mistakenly, then the TableData1 object becomes
[ null,{"employee_id" : 3816,"operation_id":3,"quantity":10}]
and the script stops working. I want to eliminate this null. What to do?

Your check if(x) is false when a 0 is entered, so TableData[row] will not be set for that entry. Instead, set your TableData using array.push:
if(x){
TableData.push({
"employee_id" : parseInt($(tr).find("input.hiddenemployeeId").val())
, "operation_id" : parseInt($(tr).find('td:eq(0)').text())
, "quantity" : parseInt($(tr).find("input.quantity").val())
})
}

If you don't care about the index values of the array, then you can use push(value) instead of array[index]=value.
like in my example:
TableData.push({
"employee_id" : parseInt($(tr).find("input.hiddenemployeeId").val()),
"operation_id" : parseInt($(tr).find('td:eq(0)').text()),
"quantity" : parseInt($(tr).find("input.quantity").val())
});`

Related

Update for progress bar of a loop with post method

I have a loop from an array and what it does is before saving it in datatable it will check if the item exsist in database and here is the code
for (i = 0, len = array.length; i < len; i++) {
var item_code = array[i][1];
var description = array[i][2];
var qty = array[i][0];
if (item_code != "") {
console.log(item_code);
var if_exsist = function () {
var tmp = null;
$.ajax({
url: "../program_assets/php/web/stocks_excel_insert_transactions.php",
data: {
saving_mode : 'check_item',
item_code : item_code
},
'async': false,
type: 'post',
success: function (data) {
var data = data.trim();
if (data == 0) {
tmp = "no"
$('#btn_save').prop('disabled', true);
} else {
tmp = "yes"
}
}
});
return tmp;
}();
tbl_delivery_list.row.add({
"docket_number" : docket_number,
"from" : from,
"from_id" : from_id,
"to" : to,
"to_id" : to_id,
"item_code" : item_code,
"description" : description,
"qty" : comma(qty),
"exsist" : if_exsist
}).draw( false );
counter++;
}
}
the code above will work but my problem is how can I incorporate a progress bar? loading sample. I add this code but the loading happens after all the work has been done.
progress = counter / array.length;
progress = progress * 100;
$(".bar").css("width", progress + "%");
my target here is to update the progress bar one by one after doing the code on the 1st one

java for fetching the one value

I need to get the emailid value from one json formated list the list is like i mentioned below
result:::[{name=sudersan san, emailid=divya.vairavel#gmail.com}, {name=Sasi Guru, emailid=ragavendran.kesavan#gmail.com }]
so please guys suggest me how can i get the emailid from above
i have tried the code in javascript for splitting.
if(data1.length >0 ){
for (var k = 0; k < data1.length; k++) {
var emailid= data1[k].emailid
var intname= data1[k].intname
var datevalue = localStorage.getItem("datevalue");
var sessiontime = localStorage.getItem("sessiontime");
$.ajax({
url: "clientinteractoremail",
type:"POST",
data : {
emailid : emailid,
datevalue : datevalue,
sessiontime : sessiontime,
intname : intname
},
success: function(data1) { },
});
}
}
var result = [
{
name="sudersan san",
emailid="divya.vairavel#gmail.com",
},
{
name="Sasi Guru",
emailid="ragavendran.kesavan#gmail.com",
}]
Those statements pull the values from this:
for(int i = 0 ; i<result.length;i++){
console.log(result[i].name);
console.log(result[i].emailid);
}
you try this

$.ajax is not working on ios Device (iphone)

On button click I am calling a function which makes a $.ajax call to get the relevant data from third party url.
It is working fine in every device and browser except ios.
Here is my button:
<input type="submit" id="continue-btn" class="button primary-btn button-type-1" value="Buy Policy" onclick="validateCardDetails();" />
Here is my js function:
function validateCardDetails() {
var todaysPaymentOption, paymentOption, nameOnCard, ccExpYear, ccExpMonth, cardNumber, cardCVVCd, cardType, accHolderName, accType, accNumber, routingNumber, paymentAmount, repetitiveDrawDate, repPaymentOption, billingFrequency, futurePaymentAmount, rep_nameOnCard, rep_ccExpYear, rep_ccExpMonth, rep_cardNumber, rep_cardType, rep_accHolderName, rep_accNumber, rep_routingNumber, rep_accType, enableAutopay, policyNumber;
var applicationId = $("#ppApplicationId").val();
todaysPaymentOption = $("#paymentMethod input[type=radio]:checked").val();
paymentOption = $("#selectedPaymentOption").val();
nameOnCard = $("#tdyFname").val();
ccExpYear = $("#ttdyexpyYear").val();
ccExpMonth = $("#ttdyexpyMonth").val();
cardNumber = $("#tdyCardnum").val();
cardCVVCd = $("#tdyCardvv").val();
var cardTypeTemp = $("#cardType input[type=radio]:checked").val();
cardType = $("#cardType").val();
accHolderName = $("#tdyAccountHolderName").val();
accType = $("#accountType option[selected]").val() ? $("#accountType option[selected]").val() : '02';
accNumber = $("#tdyBankAccount").val();
routingNumber = $("#tdyRoutingNumber").val();
paymentAmount = $("#todaysPayment").val();
// $("#refNo").text(sfs);
repetitiveDrawDate = "";
repPaymentOption = "";
billingFrequency = "";
futurePaymentAmount = "";
rep_nameOnCard = "";
rep_ccExpYear = "";
rep_ccExpMonth = "";
rep_cardNumber = "";
rep_cardTypeTemp = "";
rep_cardType = "";
rep_accHolderName = "";
rep_accNumber = "";
rep_routingNumber = "";
rep_accType = "";
enableAutopay = "false";
policyNumber = $("#policyNumber").val();
var contentObject = {
applicationID : applicationId,
todaysPaymentOption : todaysPaymentOption,
paymentOption : paymentOption,
nameOnCard : nameOnCard,
ccExpYear : ccExpYear,
ccExpMonth : ccExpMonth,
cardNumber : cardNumber,
cardCVVCd : cardCVVCd,
cardType : cardType,
accHolderName : accHolderName,
accType : accType,
accNumber : accNumber,
routingNumber : routingNumber,
paymentAmount : paymentAmount,
repetitiveDrawDate : repetitiveDrawDate,
repPaymentOption : repPaymentOption,
billingFrequency : billingFrequency,
futurePaymentAmount : futurePaymentAmount,
rep_nameOnCard : rep_nameOnCard,
rep_ccExpYear : rep_ccExpYear,
rep_ccExpMonth : rep_ccExpMonth,
rep_cardNumber : rep_cardNumber,
rep_cardType : rep_cardType,
rep_accHolderName : rep_accHolderName,
rep_accNumber : rep_accNumber,
rep_routingNumber : rep_routingNumber,
rep_accType : rep_accType,
enableAutopay : 'false',
policyNumber : policyNumber
};
// covert to query string format
var parameters = $.param(contentObject);
var paymentProcessorURL = $('#userDetailsValidatorUrl').val();
$.ajax({
type : "POST",
url : paymentProcessorURL,
crossDomain:true,
cache:false,
timeout: 15000,
data : parameters,
dataType: 'jsonp',
success : function(response) {
//response = parseJsonResponse(response);
processAjaxBillingResponse(response,todaysPaymentOption);
},
error : function(){
// if ajax call fails then handle error and display message on screen
var errorData = {"paymentAmount": paymentAmount};
var errorMessage = getPaymentErrorMessage("systemError",errorData);
showPaymentOptionsPage();
setGlobalErrorMessage("#globalValidation",errorMessage);
}
});
}

Ajax's PHP into while just working once

The code i'm trying to get to work is part of a price list of products from a db. It works almost all of it but i need one ajax to run multiple times, and it does, it even runs the success sentences but when i check the db its like it just ran once... i hope you can help me.
I take 2 values from inputs which are id and amount of the product, and i add them to the list when a button calls the send function, this is that part of the code:
function valores(cod, cant) {
if (cod != '') {
cot.push([cod, cant]);
i++;
}
return cot;
}
function send () {
event.returnValue=false;
var id = $('#id').val();
var amount = $('#cant').val();
var total;
if ($('#total').length > 0) {
total = document.getElementById('total').value;
} else {
total = 0;
}
$.ajax({
type: 'POST',
data: ({cod : id, cant : amount, tot : total }),
url: 'process/agprods.php',
success: function(data) {
$('#totals').remove();
$('#prodsadded').append(data);
valores(id, amount);
rs = $(document.getElementById('rs').html);
},
error: function () {
$('#rs').innerHTML = rs;
document.getElementById('note').innerHTML = "Error: The product doesn't exist.";
$('#handler-note').click();
}
});
}
(I translated some words to english that are originaly in spanish and to make it more readable to you)
So, the cot[] array keeps the product's id and amount, to use them in the next code, which runs when the list is complete and you hit a save button that calls this function:
function ncotiza () {
event.returnValue=false;
var nlist = $('#codp').val();
var day = $('#days').val();
$.ajax({
async: false,
type: 'POST',
data: ({listnumber: nlist, days : day}),
url: 'process/ncot.php'
});
j = 0;
while (j <= i) {
if (cot[j][0] != 0 && cot[j][1] != 0) {
var num = cot[j][0];
var cant = cot[j][1];
$.ajax({
async: false,
type: 'POST',
data: ({ listnumber : nlist, prodid: num, amount : cant }),
url: 'process/ncotpro.php',
success: function () {
alert('Success');
}
});
cot[j][0] = 0;
cot[j][1] = 0;
j++;
}
if (j == i) {
window.location.reload(1);
alert("Finished Successfully");
};
}
}
And it all runs fine, here's the PHP:
(ncot.php)
$listnumber = isset($_POST["listnumber"]) ? $_POST["listnumber"] : '';
$days = isset($_POST["days"]) ? $_POST["days"] : '';
$cons = "INSERT INTO pricelist (listnumber, diashabiles, cdate)
VALUES ('$listnumber', '$days', CURDATE())";
mysql_query($cons);
?>
(ncotpro.php)
$listnumber = isset($_POST["listnumber"]) ? $_POST["listnumber"] : '';
$prodid = isset($_POST["prodid"]) ? $_POST["prodid"] : '';
$amount = isset($_POST["amount"]) ? $_POST["amount"] : '';
$cons = "SELECT price, um
FROM inventory
WHERE listnumber = ".$prodid;
$result = mysql_query($cons) or die ("Error: ".mysql_error());
$row=mysql_fetch_assoc($result);
$umcons = mysql_query("SELECT uvalue FROM um WHERE id = ".$row["um"]) or die ("Error:".mysql_error());
$umres = mysql_fetch_assoc($umcons);
$vuum = $umres["uvalue"];
$fprice = $row["price"] * ($amount * $vuum);
$cons = "INSERT INTO cotpro (cotizacion, producto, amount, monto)
VALUES ('$listnumber', '$prodid', '$amount', '$fprice')";
mysql_query($cons) or die ("Error: ".mysql_error());
?>
The first ajax runs ok, then it also does the one that's inside the while, and it throw all the alerts but when i check the db it just made 1 row and not all it has to.
I'm sorry if it's too obvious or something, i've look a lot of questions and answers in this page and i've been trying to fix this for hours but i just dont see it.
Thank you beforehand.
Try to debug the 2nd jquery file via firebug.
what the value you return in i
while (j <= i) {
..
..
.

To function to string, search and replace function, execute function

I am trying to do something crazy, I have a JSON object of all sorts of rules for my website. I have a system set up where I can write pseudo code and then it turns it into actual code. I have this working perfectly for strings, however now I need to be able to pass functions, and replace the pseudo code inside of functions, then execute the functions.
I think I am on the right track, however when I turn a function to a string it only turns the output of the functions into a string.
Here's my JSON (part of it)
customValidation: {
//compare: "(<!this!> && <!PrimeTimeDiscount!> == 200) || (<!PrimeTimeDiscount!> == 100)",
compare: function(){
return new Validator()["date"]("<!this!>", 50);
},
overrideDefault: true
}
The commented out "compare" is how I use this system for regular strings.
And below is how I handle turning "<!this!>" and "<!*!>" into values from the JSON object. It is basically the same code twice, but the one below I have started modifying for when a function is detected.
if(typeof customValidationRule != "function")
{
var string = customValidationRule.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRule;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
}
else
{
var customValidationRuleString = customValidationRule().toString();
var string = customValidationRuleString.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRuleString;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
var backToFunction = eval('(' + execCustomValidationRule + ')');
//validation = customValidationRule();
}
validation = eval(execCustomValidationRule);

Categories