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

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

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

Beginner: Extracting multiple variables when prompted

I have the following code:
What I want to do is when I enter my prompt, I want to able to enter multiple variables and receive their outputs. How exactly do I go about doing that.
For example, when I enter lh0, lh1 and lh3, I expect to get back 000110100110010111101
var outputRef = document.getElementById('outputArea');
var output = " ";
var areas = prompt("Enter no : ");
var areas1 = {
lh0 : "0001101",
lh1 : "0011001",
lh2 : "0010011",
lh3 : "0111101",
lh4 : "0100011",
lh5 : "0110001",
lh6 : "0101111",
lh7 : "0111011",
lh8 : "0110111",
lh9 : "0001011"
};
if (areas1 [ areas ] !== undefined)
{
areas = areas1[areas];
}
output = areas;
outputRef.innerHTML = output;
Thanks!
You can use Array#split to split the string entered by the user, e.g. lh0, lh1, lh2, then find the corresponding key in the areas1 object and add it's value to the output string. Finally, display it in the DOM.
var outputRef = document.getElementById('outputArea');
var output = "";
var areas = prompt("Enter no : ");
var areas1 = {
lh0: "0001101",
lh1: "0011001",
lh2: "0010011",
lh3: "0111101",
lh4: "0100011",
lh5: "0110001",
lh6: "0101111",
lh7: "0111011",
lh8: "0110111",
lh9: "0001011"
};
areas.split(',').forEach(function(v){
output += areas1[v.replace(' ', '')];
});
outputRef.innerHTML = output;
<p id="outputArea"></p>
try this:
var outputRef = document.getElementById('outputArea');
var output = " ";
var areas = prompt("Enter no : ");
var areas1 = {
lh0 : "0001101",
lh1 : "0011001",
lh2 : "0010011",
lh3 : "0111101",
lh4 : "0100011",
lh5 : "0110001",
lh6 : "0101111",
lh7 : "0111011",
lh8 : "0110111",
lh9 : "0001011"
};
var results = [];
if (areas)
{
areas.split(',').forEach(function(val) {
results.push(areas1[val]);
});
}
outputRef.innerHTML = results.join("");
<div id="outputArea">
</div>

Javascript object structure

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())
});`

Ajax Result not Updating Web Grid Automatically MVC 4

View Script
function AddToBag()
{
var url = "/Home/Populate_Entitle/";
$.ajax({
url: url,
data: { id: 1 },
cache: false,
type: "POST",
success: function (data) {
alert("hi");
$("#gridContent").html(markup);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
Controller Functions
public ActionResult Populate_Entitle(int id)
{
if (dtEntitle.Columns.Count == 0)
{
dtEntitle.Columns.Add("sno");
dtEntitle.Columns.Add("Sport");
dtEntitle.Columns.Add("Event");
dtEntitle.Columns.Add("SubEvent");
dtEntitle.Columns.Add("Classification");
dtEntitle.Columns.Add("Entitlement");
dtEntitle.Columns.Add("Channel");
dtEntitle.Columns.Add("Brand");
dtEntitle.Columns.Add("product");
dtEntitle.Columns.Add("Unit");
dtEntitle.Columns.Add("TotalSpots");
dtEntitle.Columns.Add("TotalNetRevenue");
dtEntitle.Columns.Add("remark");
dtEntitle.Columns.Add("Sport_id");
dtEntitle.Columns.Add("Event_id");
dtEntitle.Columns.Add("SubEvent_id");
dtEntitle.Columns.Add("channel_id");
dtEntitle.Columns.Add("brand_id");
dtEntitle.Columns.Add("product_id");
dtEntitle.Columns.Add("Effective_Rate");
dtEntitle.Columns.Add("Base_Rate");
}
DataRow dr = dtEntitle.NewRow();
dr["sno"] = 1;
dr["Sport"] = "Cricket";
dr["Event"] = "IND vs BANGLADESH";
dr["SubEvent"] = "1st Day 18-JUN-2015,2nd Day 20-JUN-2015";
dr["Classification"] = "LIVE";
dr["Entitlement"] = "Spot Buys";
dr["Channel"] = "SS1,SS2";
dr["Brand"] = "Brand 1";
dr["product"] = "Product 1";
dr["Unit"] = "Spots";
dr["TotalSpots"] = 10;
dr["TotalNetRevenue"] = 200 ;
dr["remark"] = "-";
dr["Sport_id"] = 1;
dr["Event_id"] = 1;
dr["channel_id"] = 1;
dr["brand_id"] = 1;
dr["product_id"] = 1;
dr["Effective_Rate"] = 100;
dr["Base_Rate"] = 100;
dtEntitle.Rows.Add(dr);
List<Sports_Deal.Models.Entitlements> lmdEntitle = new List<Sports_Deal.Models.Entitlements>();
foreach (DataRow dr1 in dtEntitle.Rows) // loop for adding add from dataset to list<modeldata>
{
lmdEntitle.Add(new Sports_Deal.Models.Entitlements
{
Event = dr1["Event"].ToString(),
Base_Rate = Convert.ToInt32(dr1["Base_rate"]),
brand_id = Convert.ToInt32(dr1["brand_id"]),
Brand = dr1["brand"].ToString(),
Channel = dr1["Channel"].ToString(),
Sport = dr1["Sport"].ToString(),
Effective_Rate = Convert.ToInt32(dr1["Effective_Rate"]),
channel_id =(dr1["channel_id"]).ToString(),
Quality = (dr1["channel_id"]).ToString(),
Classification = dr1["Classification"].ToString(),
Entitlement = dr1["Entitlement"].ToString(),
Event_id = Convert.ToInt32(dr1["Event_id"]),
product_id = Convert.ToInt32(dr1["Product_id"]),
remark = dr1["remark"].ToString(),
sno = Convert.ToInt32(dr1["sno"]),
Sport_id = Convert.ToInt32(dr1["Sport_id"]),
SubEvent = dr1["SubEvent"].ToString(),
SubEvent_id = dr1["SubEvent_id"].ToString (),
TotalNetRevenue = Convert.ToInt32( dr1["TotalNetRevenue"]),
TotalSpots = Convert.ToInt32(dr1["TotalSpots"]),
Unit = dr1["Unit"].ToString()
});
}
return PartialView("markup", lmdEntitle);
}
}
I need to populate Web grid dybamically when controller method returns list.
Replace your markup with the Data
function AddToBag() {
var url = "/Home/Populate_Entitle/";
$.ajax({
url: url,
data: { id: 1 },
cache: false,
type: "POST",
success: function (data) {
alert("hi");
$("#gridContent").html(data);
},
error: function (reponse) {
alert("error : " + Json.stringify(reponse));
}
});
}
You are getting data in response, markup is undefined for this criteria

Yui Datatable with AutoComplete and Pagination

I try to understand how use server-side Pagination for Dynamic Data (I see example : http://developer.yahoo.com/yui/examples/datatable/dt_dynamicdata.html).
My problem is I can not customize my request, when I try the pagination, my request is :
qct-list.htmlsort=geneid&dir=asc&startIndex=50&result=25
The request should be in the following form :
qct-list.html?name=cd4&symbol=cd4&start=0&limit=25 or
qct-list.html?name=cd4&symbol=cd4&start=25&limit=50 ...
Here is a copy (part) of my code :
var myColumnDefs = [
{key:"geneid", label:"Gene", sortable:true},
{key:"name", label:"Name", sortable:true},
{key:"symbol", label:"Symbol", sortable:true},
{key:"lastupdated", label:"Last Updated", formatter:"date", sortable:true},
{key:"lastmodified", label:"Last Modified", formatter:"date", sortable:true}
];
var myDataSource = new YAHOO.util.DataSource("qct-list.html");
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.connXhrMode = "queueRequests";
myDataSource.responseSchema = {
resultsList: "geneItemList",
fields: ["col","qv","limit","start","geneid","name","symbol","lastupdated","lastmodified"],
metaFields: {
totalRecords: "totalRecords" // Access to value in the server response
}
};
var qctPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 25,
totalRecords : YAHOO.widget.Paginator.VALUE_UNLIMITED,
template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions: [25,50,75,100]
});
var myRequestBuilder = function(ostate, oSelf) {
oState = oState || {pagination:null};
var name = Dom.get('dt_input_name').value;
var symbol = Dom.get('dt_input_symbol').value;
var start = (oState.pagination) ? oState.pagination.recordOffset : 0;
var limit = (oState.pagination) ? oState.pagination.rowsPerPage : 25;
return "?name=" + name + "&symbol"+ symbol + "&start=" + start + "&limit=" + limit;
}
var oConfigs = {
dynamicData: true, // Enables dynamic server-driven data
selectionMode: "single",
paginator: qctPaginator ,
generateRequest : myRequestBuilder,
paginationEventHandler : YAHOO.widget.DataTable.handleDataSourcePagination,
initialRequest: "?name=&symbol=&start=0&limit="
};
var myGeneListTable = new YAHOO.widget.DataTable("geneListTable", myColumnDefs, myDataSource, oConfigs);
myGeneListTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
Can someone explain how to use the pagination with DataTable and how to personalize request ?
I almost managed to make it work my pagination.
My RequestBuilder now works fine, I get the request I need :
qct-list.html?name=interferon&symbol=&start=25&limit=25
Here the new code :
var myColumnDefs = [
{key:"geneid", label:"Gene", sortable:true},
{key:"name", label:"Name", sortable:true},
{key:"symbol", label:"Symbol", sortable:true},
{key:"lastupdated", label:"Last Updated", formatter:"date", sortable:true},
{key:"lastmodified", label:"Last Modified", formatter:"date", sortable:true}
];
var myDataSource = new YAHOO.util.DataSource("qct-list.html");
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.connXhrMode = "queueRequests";
myDataSource.responseSchema = {
resultsList: "geneItemList",
fields: ["col","qv","limit","start","geneid","name","symbol","lastupdated","lastmodified"],
metaFields: {
totalRecords: "totalRecords" // Access to value in the server response
}
};
var qctPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 25,
rowsPerPageOptions: [25,50,75,100]
});
var myRequestBuilder = function(oState,oSelf)
{
oState = oState || {pagination:null, sortedBy:null};
// var sort = (oState.sortedBy) ? oState.sortedBy.key : "geneid";
// var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
var start = (oState.pagination != null) ? oState.pagination.recordOffset : 0;
var limit = (oState.pagination != null) ? oState.pagination.rowsPerPage : 25;
var name = Dom.get('dt_input_name').value || "";
var symbol = Dom.get('dt_input_symbol').value || "";
return '?name='+ name + '&symbol=' + symbol + '&start='+ start + '&limit=' + limit;
}
var oConfigs = {
initialRequest: "?name=interferon&symbol=&start=&limit=",
dynamicData: true, // Enables dynamic server-driven data
selectionMode: "single",
paginator: qctPaginator,
generateRequest : myRequestBuilder
};
var myGeneListTable = new YAHOO.widget.DataTable("geneListTable", myColumnDefs, myDataSource, oConfigs);
myGeneListTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
if (oPayload == undefined) {
oPayload = {};
}
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
I think you need to swap the declaraion of oConfigs and myRequestBuilder around so that
var myRequestBuilder = ...
var oConfigs = ...

Categories