how to add attribute "selected" jquery - javascript

I use https://geodata.solutions
I'm trying to add the "selected" attribute to the country option germany, I have a parameter "$ user ['country']" that says the value "Germany" if someone has encountered this problem and knows how to solve it. i can't figure out where the javascript code checks where to put the selected attribute*$user[country']; // Germany*
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
}
var errorRes = function(e) {
console.log(e);
//alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
//jQuery('#loader').modal('hide');
}
jQuery.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
var rootUrl = "//geodata.solutions/api/api.php";
//set default values
var username = 'demo';
var ordering = 'name';
//now check for set values
var addParams = '';
if(jQuery("#gds_appid").length > 0) {
addParams += '&appid=' + jQuery("#gds_appid").val();
}
if(jQuery("#gds_hash").length > 0) {
addParams += '&hash=' + jQuery("#gds_hash").val();
}
var call = new ajaxCall();
this.confCity = function(id) {
// console.log(id);
// console.log('started');
var url = rootUrl+'?type=confCity&countryId='+ jQuery('#countryId option:selected').attr('countryid') +'&stateId=' + jQuery('#stateId option:selected').attr('stateid') + '&cityId=' + id;
var method = "post";
var data = {};
call.send(data, url, method, function(data) {
if(data){
// alert(data);
}
else{
// alert('No data');
}
});
};
this.getCities = function(id) {
jQuery(".cities option:gt(0)").remove();
//get additional fields
var stateClasses = jQuery('#cityId').attr('class');
var cC = stateClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = '&addClasses=' + encodeURIComponent(acC);
}
var url = rootUrl+'?type=getCities&countryId='+ jQuery('#countryId option:selected').attr('countryid') +'&stateId=' + id + addParams + addClasses;
var method = "post";
var data = {};
jQuery('.cities').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.cities').find("option:eq(0)").html("Select City");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded count:' + data.hits + ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' + data.hits + ' of 1000')
}
var listlen = Object.keys(data['result']).length;
if(listlen > 0)
{
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
jQuery('.cities').append(option);
});
}
else
{
var usestate = jQuery('#stateId option:selected').val();
var option = jQuery('<option />');
option.attr('value', usestate).text(usestate);
option.attr('selected', 'selected');
jQuery('.cities').append(option);
}
jQuery(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getStates = function(id) {
jQuery(".states option:gt(0)").remove();
jQuery(".cities option:gt(0)").remove();
//get additional fields
var stateClasses = jQuery('#stateId').attr('class');
var cC = stateClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = '&addClasses=' + encodeURIComponent(acC);
}
var url = rootUrl+'?type=getStates&countryId=' + id + addParams + addClasses;
var method = "post";
var data = {};
jQuery('.states').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.states').find("option:eq(0)").html("Select State");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded:' + data.hits + ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' + data.hits + ' of 1000')
}
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
option.attr('stateid', key);
jQuery('.states').append(option);
});
jQuery(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
//get additional fields
var countryClasses = jQuery('#countryId').attr('class');
var cC = countryClasses.split(" ");
cC.shift();
var addClasses = '';
if(cC.length > 0)
{
acC = cC.join();
addClasses = '&addClasses=' + encodeURIComponent(acC);
}
var presel = false;
var iip = 'N';
jQuery.each(cC, function( index, value ) {
if (value.match("^presel-")) {
presel = value.substring(7);
}
if(value.match("^presel-byi"))
{
var iip = 'Y';
}
});
var url = rootUrl+'?type=getCountries' + addParams + addClasses;
var method = "post";
var data = {};
jQuery('.countries').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
jQuery('.countries').find("option:eq(0)").html("Select Country");
if(data.tp == 1){
if(data.hits > 1000)
{
//alert('Free usage far exceeded. Please subscribe at geodata.solutions.');
console.log('Daily geodata.solutions request limit exceeded:' + data.hits + ' of 1000');
}
else
{
console.log('Daily geodata.solutions request count:' + data.hits + ' of 1000')
}
if(presel == 'byip')
{
presel = data['presel'];
console.log('2 presel is set as ' + presel);
}
if(jQuery.inArray("group-continents",cC) > -1)
{
var $select = jQuery('.countries');
console.log(data['result']);
jQuery.each(data['result'], function(i, optgroups) {
var $optgroup = jQuery("<optgroup>", {label: i});
if(optgroups.length > 0)
{
$optgroup.appendTo($select);
}
jQuery.each(optgroups, function(groupName, options) {
var coption = jQuery('<option />');
coption.attr('value', options.name).text(options.name);
coption.attr('countryid', options.id);
if(presel) {
if (presel.toUpperCase() == options.id) {
coption.attr('selected', 'selected');
}
}
coption.appendTo($optgroup);
});
});
}
else
{
jQuery.each(data['result'], function(key, val) {
var option = jQuery('<option />');
option.attr('value', val).text(val);
option.attr('countryid', key);
if(presel)
{
if(presel.toUpperCase() == key)
{
option.attr('selected', 'selected');
}
}
jQuery('.countries').append(option);
});
}
if(presel)
{
jQuery('.countries').trigger('change');
}
jQuery(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
jQuery(function() {
var loc = new locationInfo();
loc.getCountries();
jQuery(".countries").on("change", function(ev) {
var countryId = jQuery("option:selected", this).attr('countryid');
if(countryId != ''){
loc.getStates(countryId);
}
else{
jQuery(".states option:gt(0)").remove();
}
});
jQuery(".states").on("change", function(ev) {
var stateId = jQuery("option:selected", this).attr('stateid');
if(stateId != ''){
loc.getCities(stateId);
}
else{
jQuery(".cities option:gt(0)").remove();
}
});
jQuery(".cities").on("change", function(ev) {
var cityId = jQuery("option:selected", this).val();
if(cityId != ''){
loc.confCity(cityId);
}
});
});
<select name="country" class="countries" id="countryId">
<option value="">Select Country</option>
</select>
<select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
<select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
after run javascript:
<select name="country" class="countries form-control" id="countryId">
<option value="">Select Country</option>
<option value="Afghanistan" countryid="AF">Afghanistan</option>
<option value="Albania" countryid="AL">Albania</option>
<option value="Algeria" countryid="DZ">Algeria</option>
<option value="Germany" countryid="DE">Germany</option> <!-- add attr selected-->
</select>

Related

Debugger not reaching select statement in jQuery.autocomplete

I have a Dynamic Grid in the ASP.NET page. When I click Add User, it creates an empty record with Textbox controls and when the user types something in the first Textbox - UserName, it should pull the UserNames from the Database and autocomplete should work for that Textbox control.
I have implemented jQuery.autocomplete function as below.
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
var rows = data.split("|");
var jsStr = "var datalist=[";
for (i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace("'", "\\'");
s = s.replace('"', "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",name:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (datalist) != 'undefined') {
response(jQuery.map(datalist, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
When I try to Debug this autocomplete, the data is coming at the end of response(jQuery.map(datalist, function (items) statement. But the select: option is not firing.
EDIT
The below screenshot shows how the data is formed.
And this is what is present in the Server-Side Users.aspx.vb Page_Load Event
Response.Clear()
Response.Write(GetUserName(Request.QueryString("UserName")))
Response.End()
What could be the problem?
First. In the response, you check the data variable in swith. And you get it as a string.
Second. the best way to work with ajax is JSON.
jQuery.ajax({
url: url,
dataType: 'json'
On successful response:
Make parsing.
json = JSON.parse(data)
And then you already apply your logic, I work with individual object variables.
swith(json.string){ .... }
And it will be easier to fill Textbox controls with the necessary parameters: json.user - the variable will contain an array of data about users.
Update code:
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
dataType: 'json',
/*
* format respone data (string!!!) -> {"result": [{"id": 1,"item": 2},{"id": 1,"item": 2}],"found": "VALUESFOUND"}
*/
success: function (data) {
let json = JSON.parse(data);
switch (json.found) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
response(jQuery.map(json.result, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});

Textbox to values goes into round number

I bought a PHP script (https://codecanyon.net/item/easy-inventory) for distributor agency. but when I tried to add quantity like 2.55, it turned to 255. First one is textbox code and second one is JS. when I remove onblur ="order(this); "I can enter 2.55 value into textbox but the calculation is not processing. check image:
<td class="vertical-td">
<input type="number" name="qty" style="width: 90px" value="<?php echo $item['qty'] ?>" onblur ="order(this);" id="<?php echo 'qty'.$item['rowid'] ?>" class="form-control">
</td>
Here is JS code
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
$(document).ready(function() {
/*place jQuery actions here*/
var req = getXMLHTTP();
if (req) {
var link = getBaseURL();
//*********************************************
// purchase product Item add to cart
//*********************************************
//$("table.purchase-products form").submit(function () {
//
// var id = $(this).find('input[name=product_id]').val();
//
// $.post(link + "admin/purchase/add_cart_item", {product_id: id, ajax: '1'},
// function (data) {
//
// if (data == 'true') {
//
// $.get(link + "admin/purchase/show_cart", function (cart) {
// $("#cart_content").html(cart);
// });
//
// }
//
// });
//
// return false;
//});
//*********************************************
// add new product to purchase cart
//*********************************************
$("#add-product form").submit(function () {
var product_name = $(this).find('input[name=product_name]').val();
var qty = $(this).find('input[name=qty]').val();
var price = $(this).find('input[name=price]').val();
$.post(link + "admin/purchase/add_new_product_to_cart", {
product_name: product_name,
qty: qty,
price: price,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
$("#newform")[0].reset();
});
}
});
return false;
});
}
});
//*********************************************
// Get Base URL
//*********************************************
function getBaseURL() {
return link = $('body').data('baseurl');
};
//*********************************************
// Update cart purchase cart item
//*********************************************
function purchase(arg){
$('#btn_purchase').attr('disabled','disabled');
var val = arg.getAttribute('id');
var id = val.slice(3);
// do your stuff
var qty = $( "#qty"+id ).val();
var price = $( "#pri"+id ).val();
//alert(price);
var link = getBaseURL();
$.post(link + "admin/purchase/update_cart_item", {rowid: id, qty: qty, price: price ,ajax: '1'},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
});
}
});
}
//*********************************************
// Update order cart item
//*********************************************
function order(arg){
$('#btn_order').attr('disabled','disabled');
var req = getXMLHTTP();
if (req) {
var val = arg.getAttribute('id');
var id = val.slice(3);
// do your stuff
var qty = $("#qty" + id).val();
var price = $("#pri" + id).val();
var product_code = $("#code" + id).val();
if($("#opt" + id).prop("checked") == true){
var custom_price = 'on';
}
var link = getBaseURL();
if(qty && price && product_code)
$.post(link + "admin/order/update_cart_item", {
rowid: id,
qty: qty,
price: price,
product_code: product_code,
custom_price: custom_price,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart", function (cart) {
$("#cart_content").html(cart);
});
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
//$('#btn_order')..removeAttr('disabled');
}
});
}
}
//*********************************************
// Custom Price Operation
//*********************************************
function price_checkbox(me)
{
var val = me.id
var id = val.slice(3);
//alert(id);
var result = $("#pri" + id).prop('disabled');
if(result){
$("#pri" + id).prop('disabled',false);
}else{
$("#pri" + id).prop('disabled',true);
}
if(result == false){
$('#btn_order').attr('disabled','disabled');
var req = getXMLHTTP();
if (req) {
// do your stuff
var qty = $("#qty" + id).val();
var price = $("#pri" + id).val();
var product_code = $("#code" + id).val();
var custom_price = 'unchecked';
var link = getBaseURL();
$.post(link + "admin/order/update_cart_item", {
rowid: id,
qty: qty,
price: price,
product_code: product_code,
custom_price: custom_price,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/order/show_cart", function (cart) {
$("#cart_content").html(cart);
});
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
}
//*********************************************
// Customer phone number check
//*********************************************
function check_phone(phone) {
var customer_id = $("#customer_id").val();
//alert(customer_id);
var link = getBaseURL();
var strURL = link + "admin/customer/check_customer_phone/" + phone + "/" + customer_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
document.getElementById('phone_result').innerHTML = result;
if (result) {
$('#customer_btn').prop('disabled', true);
} else {
$('#customer_btn').prop('disabled', false);
}
validation_check();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//*********************************************
// Employee user name check
//*********************************************
function check_user_name(str) {
$('#sbtn').attr('disabled','disabled');
var user_name = $.trim(str);
var user_id = $.trim($("#employee_id").val());
var link = getBaseURL();
//alert(link);
var strURL = link + "admin/global_controller/check_existing_user_name/" + user_name + "/" + user_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
document.getElementById('username_result').innerHTML = result;
var msg = result.trim();
if (msg) {
document.getElementById('sbtn').disabled = true;
} else {
document.getElementById('sbtn').disabled = false;
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//*********************************************
// Product Category to Subcategory
//*********************************************
function get_category(str) {
if (str == '') {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
} else {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
var link = getBaseURL();
var strURL = link + "admin/product/get_subcategory_by_category/" + str;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
//alert(result);
$("#subcategory").html("<option value=''>Select Subcategory</option>");
$("#subcategory").append(result);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
}
//*********************************************
// Change Password method div show hide
//*********************************************
function setVisibility() {
var a = $('#change_password').val();
var result = a.toString()
if( result == 'Change Password'){
$('#change_password').val('Hide Password'),
$('#password_flag').val('ok'),
$('#password_div').show();
}else{
$('#change_password').val('Change Password'),
$('#password_flag').val('no'),
$('#password_div').hide();
}
}
//*********************************************
// Purchase payment method show hide
//*********************************************
$(function() {
$('#payment_type').change(function(){
$("#pri" + id).prop('disabled',false);
if(val == 'cheque')
{
$('#payment').show();
}
else if (val == 'card')
{
$('#payment').show();
} else
{
$('#payment').hide();
}
});
});
//*********************************************
// Order payment method show hide
//*********************************************
$(function() {
$('#order_payment_type').change(function(){
var val = $( "#order_payment_type" ).val();
if(val == 'cheque')
{
$('#payment').show();
}
else if (val == 'card')
{
$('#payment').show();
} else
{
$('#payment').hide();
}
});
});
//*********************************************
// Order Confirmation Method
//*********************************************
$(function() {
$('#order_confirmation').change(function(){
var val = $( "#order_confirmation" ).val();
if(val == '2')
{
$('#payment_method_block').show();
}else
{
$('#payment_method_block').hide();
}
});
});
//*********************************************
// Email Campaign
//*********************************************
$("#sendEmail form").submit(function () {
var campaign_id = $(this).find('input[name=campaign_id]').val();
var req = getXMLHTTP();
if (req) {
var link = getBaseURL();
$.post(link + "admin/campaign/send_email", {
campaign_id: campaign_id,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
$("#newform")[0].reset();
});
}
});
return false;
}
});
//*********************************************
// Update Discount %
//*********************************************
function discountValue(discount) {
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/order/assign_discount", {
discount: discount,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
function getCustomer(customer) {
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/order/get_customer", {
customer_id: customer.value,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
//*********************************************
// Product Code check
//*********************************************
function check_product_code(str) {
$('#submit').attr('disabled','disabled');
var product_code = $.trim(str);
var product_id = $.trim($("#product_id").val());
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/product/check_product_code", {
product_code: product_code,
product_id: product_id,
ajax: '1'
},
function (data) {
if (data) {
document.getElementById('product_code_result').innerHTML = data;
document.getElementById('submit').disabled = true;
} else {
document.getElementById('submit').disabled = false;
$('#product_code_result').empty();
}
});
}
}

How to deal with asynchronous problems in javascript

I want to display data stored in ch ! But my problem is that ch is displayed before the data is stored !
I think this is an Asynchronous Problems! How can I solve this problem.
When I try to get length of ch, I get always 0. Even if I store data statically in ch, I get the length 0.
I think this is an Asynchronous Problems! How can I solve this problem.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
$.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml",
success: function(xml) {
var stock = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function()
{
dossier = $(this).attr('dossier');
stock.push(dossier);
});
});
var ch = [];
for (var i = 0; i < stock.length; i++) {
$.ajax({
url: "/mySecondWebServiceURL" + stock[i],
type: "GET",
dataType: "xml",
success: function(xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
ch.push({
"nom": nom,
"matcle": matcle,
"dossier": dossier
});
if ($('#population').val() != null && firstIter == false) {
}
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
The problem is that you are not waiting for the second service to respond.
It should be something like this:
const deferreds = stock.map((stockItem) => {
//... your logic with ch.push here
return $.ajax({
// your call to the second service
});
});
$.when(...deferreds).then(() => {
// your code
// for (var key in ch) {
});
The approach I'd rather take is to break the code down and use Promises. You really should take your time to learn Promises. It's a JavaScript standard and what jQuery uses under the hood.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
return $.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml"
});
}
function getStockArray(xml) {
var stocks = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function() {
{
dossier = $(this).attr('dossier');
stocks.push(dossier);
});
});
});
return stocks;
}
function getStocks(stocks) {
return Promise.all(stocks.map(fetchStock));
}
function fetchStock (stock) {
return $.ajax({
url: "/mySecondWebServiceURL" + stock,
type: "GET",
dataType: "xml"
})
.then(formatStockInfo)
}
function formatStockInfo (xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
if ($('#population').val() != null && firstIter == false) {
}
return {
"nom": nom,
"matcle": matcle,
"dossier": dossier
};
}
function updateSelectMenu (ch) {
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
}
RechercheFiltrée()
.then(getStockArray)
.then(getStocks)
.done(updateSelectMenu);

Creating an image file dynamically with Javascript

I'm trying to create an image file dynamically, based on the contents retrieved from S3 Bucket. Got CORS working fine, here's the code I've written:
/**
* #name fetchFile
* #desc Fetch the desired file, and add to our _filesPending array, and update dialog process
* #author cgervais
*/
var _filesPending = [];
var _fileMessageDialog = "Currently downloading {{numberOfFiles}} videos...";
var _filesDownloadedSoFar = 0;
var _filesDownloaded = [];
var downloading = false;
function OKDownload(response, fileName) {
var responsePerfect = {
link: function() {
var _tmpResponse = JSON.parse(response);
return _tmpResponse.location;
}
};
$.ajax({
type: "GET",
url: responsePerfect.link(),
data: {},
success: function(answer) {
var _tmpFileObject = {
fUrl: fileName,
fContent: btoa(unescape(encodeURIComponent(answer.trim())))
};
_filesDownloaded.push(_tmpFileObject);
_filesDownloadedSoFar = _filesDownloadedSoFar + 1;
console.log('Downloaded -- so far: ' + _filesDownloadedSoFar);
},
error: function(response, errorCode, errorMessage) {
console.log('[OKDownload] ' + response + ' - ' + errorCode + ' - ' + errorMessage + ' // ' + responsePerfect.link);
}
})
}
var _alreadyGeneratedRStrings = [];
function generateReasonableString(min, max, fnMax) {
var _genStringSeed = Date.now() + 10;
var _randomString = '';
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=min; i < max; i++ )
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
_randomString = btoa(text + '::' + _genStringSeed);
if(_randomString.indexOf('==') > -1) {
_randomString = _randomString.replace('==','');
}
if(_randomString.length > fnMax) {
_randomString = _randomString.substring(0, fnMax);
}
if(_alreadyGeneratedRStrings.indexOf(_randomString) > -1) { _randomString = generateReasonableString(min, max, fnMax); }
_alreadyGeneratedRStrings.push(_randomString);
return _randomString;
}
function httpRawFetch(link) {
var matched = generateReasonableString(8, 26, 8) + ".jpg";
$.ajax({
type: "GET",
url: link.href + "&rawlink=yes",
data: {},
success: function(answer) {
if(answer === "") { console.log('[httpRawFetch] Failed fetching ' + link); return; }
OKDownload(answer, matched);
},
error: function(response, errorCode, errorMessage) {
console.log('[httpRawFetch] Error fetching JSON data from backend server.');
console.log('[DEBUG] ' + response + ' - ' + errorCode + ' - ' + errorMessage);
console.log('[DEBUG] Link: ' + link);
}
})
}
function generateDownloadModal() {
var _tmpHTML;
// #TODO: generate side modal with jQuery
}
function downloadFinished() {
var zip = new JSZip();
var _runningCountOfFiles = 0;
var _runningAddFiles = true;
for(var i = 0; i < _filesDownloaded.length; i++) {
_runningAddFiles = true;
// zip create file ( fileName, fileContent )
zip.file(_filesDownloaded[i].fUrl, decodeURIComponent(escape(atob(_filesDownloaded[i].fContent))));
_runningCountOfFiles++;
}
var recInterval = setInterval(function() {
if(_runningAddFiles && _runningCountOfFiles == _filesDownloaded.length || _runningCountOfFiles > _filesDownloaded.length) {
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "recordings.zip");
_runningAddFiles = false;
clearInterval(recInterval);
});
}
}, 1000);
}
setInterval(function() {
if(downloading) {
if(_filesDownloadedSoFar === _filesDownloaded.length) {
downloadFinished();
downloading = false;
}
}
}, 60000);
function fetchFile(link) {
if(link === "") {
alert('Cannot download this file.');
return;
}
_filesPending.push(link);
httpRawFetch(link);
downloading = true;
}
The issue:
It creates the zip with files, then it downloads to my machine. I open the image file, I get an error (all of them): "We can't open this file"
What am I doing wrong? They're JPG images.

dropdownlistfor cannot change to selected value from controller with jquery

I have read through this question ASP.NET MVC DropDownListFor not selecting value from model and answer but I don't know the solution to my problem.
This is part of my controller, here is first time when I call the ddl for the view, but not yet select any value.
private void bindDDLRefund(FormModel mod){
// refundCodes = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).Select(e => e.RefundCode).FirstOrDefault();
mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).ToList().Select(e => new SelectListItem { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString() }).OrderBy(e => e.Value);
//mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted == false).ToList().Select(e => new SelectListItem() { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString(), Selected = (e.RefundCode == mod.RefundCode) }).ToList();
}
public ActionResult Add(){
var mod = new FormModel();
//var percentage = GetAllPercentage();
//mod.ddlRefundPercentage = GetSelectListItems(percentage);
bindDDLRefund(mod);
mod.isCreate = true;
return View("Form",mod);
}
Then here is the selected value is being selected from controller,
public JsonResult GetTicketData(string ticketnumber){
bool isSuccess = false;
var result = new spRefTicketRefundRetrieve();
int isError = 0;
string errorDesc = "";
var mod = new FormModel();
try{
spRefTicketRefundRetrieveHeader obj = _uow.StoreProc.spRefTicketRefundRetrieve(ticketnumber);
isError = obj.IsError;
errorDesc = obj.ErrorDesc;
if (obj.IsError == 0){
result = obj.detailData;
}
isSuccess = true;
}
catch (Exception ex){
Logger.LogError("Reload Ticket Data", "Id = " + ticketnumber, ex);
}
return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetRefundData(string refund_id)
{
bool isSuccess = false;
var result = new spRefTicketRefundDetail();
int refundId = Encryption.Decrypt(refund_id);
try
{
result = _uow.StoreProc.spRefTicketRefundDetail(refundId);
isSuccess = true;
}
catch (Exception ex)
{
Logger.LogError("Reload Refund Data", "Id = " + refundId, ex);
}
return Json(new { success = isSuccess, value = result }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetCFData(string ticketNumber, string refundCode)
{
bool isSuccess = false;
var result = new spRefTicketRefundChangeCF();
int isError = 0;
string errorDesc = "";
try
{
spRefTicketRefundChangeCFHeader obj = _uow.StoreProc.spRefTicketRefundChangeCF(ticketNumber, refundCode);
isError = obj.IsError;
errorDesc = obj.ErrorDesc;
if (obj.IsError == 0)
{
result = obj.listData;
}
isSuccess = true;
}
catch (Exception ex)
{
Logger.LogError("Reload CF Data", "Id = " + ticketNumber, ex);
}
return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
}
The selected value is about CfPercentage and variable result contains CF_PERCENTAGE which is representate of CfPercentage,
And here is my view and jQuery;
#Html.DropDownListFor(e => e.RefundCode, Model.DdlRefundPercentage, new { #class = "form-control", id= "ddl-refund",onchange="CFChange();" })
var GetRefundData = function (refundId) {
$.ajax({
url: '#Url.Action("GetRefundData")',
type: 'POST',
data: { refund_id: refundId },
success: function (result) {
console.log(result);
if (result.success) {
SetFormDetail(result.value);
}
else
{
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var GetRefundViewData = function (refundId) {
$.ajax({
url: '#Url.Action("GetRefundData")',
type: 'POST',
data: { refund_id: refundId },
success: function (result) {
console.log(result);
if (result.success) {
SetFormView(result.value);
}
else {
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var GetTicketData = function (ticketNumber) {
var target = $("#loading");
$.ajax({
beforeSend: function () {
target.html('<img src="#Url.Content("~/Content/images/ajax-loader.gif")"> loading...');
$('#divForm').css('display', 'none');
},
url: '#Url.Action("GetTicketData")',
type: 'POST',
data: { ticketnumber: ticketNumber },
success: function (result) {
console.log(result);
if (result.success) {
target.html('');
if (result.isError == "0") {
$('#divForm').css('display', 'block');
$('#txtHiddenTicketNumber').val(ticketNumber);
SetForm(result.value);
GetCFData();
}
else {
alert(result.errorDesc);
}
}
else {
$("#loading").html('');
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var CFChange = function ()
{
GetCFData();
};
var GetCFData = function ()
{
var TicketNumber = $('#txtHiddenTicketNumber').val();
var RefundCode = $("#ddl-refund option:selected").val();
$.ajax({
url: '#Url.Action("GetCFData")',
type: 'POST',
data: { ticketNumber: TicketNumber, refundCode: RefundCode },
success: function (result) {
console.log(result);
if (result.success) {
SetCFDetail(result.value);
}
else {
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var SetForm = function(list){
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.TICKET_USED);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#txtReason').val('');
$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR);
});
};
var SetFormDetail = function (list) {
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.USED_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#txtReason').val(this.DESCRIPTION);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
//$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
$("#ddl-refund").val(this.REFUND_CODE);
});
//GetCFData();
};
var SetFormView = function (list) {
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.USED_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#lblPaymentType').html(this.PAYMENT_TYPE);
$('#lblReason').html(this.DESCRIPTION);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
//$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
$("#ddl-refund").val(this.REFUND_CODE);
});
//GetCFData();
};
var SetCFDetail = function (list) {
$(list).each(function () {
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
});
};
After I running this, the view is always not select percentage based on sp that is relevant to ticketnumber. I have tried to modified it but nothing works. feel happy to be help :)
This line,
$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR)
It actually set's the currently selected option's text to whatever value in this.CANCELLATION_FEE_PERCENTAGE_STR . It won't actually change the selected option. You can see it in action here.
What you should be doing Get the RefundCode value from your server call, and pass that in the val() method to set specific option item as the selected item.
Assuming your razor rendered your dropdown with this markup.
<SELECT id="ddl-refund">
<option value="25">Twenty Five</option>
<option value="26">Twenty Six</option>
<option value="28">Twenty Eight</option>
<option value="29">Twenty Nine</option>
And json data you received from your server call has a property called RedundCode.
$(list).each(function () {
$("#ddl-refund").val(this.RefundCode);
}
It will work if this.RefundCode is either 25 or 26 or 28 or 29.
I am not quite sure, why you are sending an array when all you want to send is a single item. But that is a different thing to fix.

Categories

Resources