This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have problem with this line
console.log("xxx" + stanica1);
Result is xxxundefined but i need return value stanica1Prosjek/24;
function podatciPrethodniDan(handleData) {
var parametar = $("#parametar1").val();
$.ajax({
type: "POST",
url: "php/getPreviousDayData.php",
dataType: "json",
data: {
parametar: parametar
},
success: function(data) {
handleData(data);
} //end of success
}); //end of ajax
}
function style(feature) {
var stanica1;
stanica1 = podatciPrethodniDan(function(output) {
//console.log(output);
var stanica1Prosjek = 0;
var stanica2Prosjek = 0;
var stanica3Prosjek = 0;
var stanica4Prosjek = 0;
//console.log(output.length);
for (i = 0; i < output.length; i++) {
//console.log("petlja " + i);
if (i < 24) {
stanica1Prosjek = stanica1Prosjek + parseFloat(output[i].par);
//console.log(stanica1Prosjek + " " + i);
}
}
console.log("in" + stanica1Prosjek);
return stanica1Prosjek / 24;
});
console.log("xxx" + stanica1);
}
Define you var out of functions.
Example:
var demo = 12;
function ok () {
demo += 3;
}
function ok2 () {
demo+= 5;
}
console.log( demo ); // return 12
ok();
console.log( demo ); // return 15
ok2():
console.log( demo ); // return 20
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have some code like this
I have load function, it call testRequest function.
testRequest function call ajax service and return response.
But after testRequest function run success, load function get undefined value
angular.module('MyApp', []).controller("AppCtrl", ['AjaxService', function(ajax) {
var l_this = this;
this.testRequest = function() {
var req = ajax.getstatus('https://testapi.io/api/nguyenthemanh2601/testangular');
req.then(function(rep) {
var arr = [];
if (rep.status == 400) {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
} else {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
}
});
};
this.load = function() {
var res = l_this.testRequest();
console.log(res);
l_this.status = res;
}
}]);
Please help!
angular.module('MyApp', []).controller("AppCtrl", ['AjaxService', function(ajax) {
var l_this = this;
this.testRequest = function() {
$http({
method: 'POST',
url: 'https://testapi.io/api/nguyenthemanh2601/testangular',
}).
success(function(rep) {
if (rep.status == 200) {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
}
}).
error(function(rep) {
if (rep.status == 400) {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
}
});
};
// Next Execution.....
}]);
Note You can handle success and error message based on that response execute the next step(handle error and success).
more info... $http request angular
console.log (dict) will give you
{"click here:":{"message":"点击这里"},"apply":{"message":"应用"},"a translation test!":{"message":"js翻译示例!"},"tabLanding":"欢迎","tabSetup":{"message":"安装"}}
I want tabSetup appear like 安装 in html
here is the html code:
<li class="tab_setup"></li>
what i see is it does not shows correctly just showed as [object Object]
it should showed as 安装
here is my java-script. Thanks
var dict = {};
var systemLang = navigator.language.toLowerCase().slice(0,2);
$(function () {
registerWords();
switch(getCookieVal("lang")) {
case "en" :
setLanguage("en");
break
case "zh" :
setLanguage("zh");
break
default:
setLanguage(systemLang);
}
console.log (dict);
console.log(JSON.stringify(dict));
// 切换语言事件
$("#enBtn").bind("click", function () {
setLanguage("en");
});
$("#zhBtn").bind("click", function () {
setLanguage("zh");
});
// $("#applyBtn").bind("click", function () {
// alert(__tr("a translation test!"));
// });
});
function setLanguage(lang) {
setCookie("lang=" + lang + "; path=/;");
translate(lang);
}
function getCookieVal(name) {
var items = document.cookie.split(";");
for (var i in items) {
var cookie = $.trim(items[i]);
var eqIdx = cookie.indexOf("=");
var key = cookie.substring(0, eqIdx);
if (name == $.trim(key)) {
return $.trim(cookie.substring(eqIdx + 1));
}
}
return null;
}
function setCookie(cookie) {
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = cookie+ ";expires=" + exp.toGMTString();
}
function translate(lang) {
if(sessionStorage.getItem(lang + "Data") != null){
dict = JSON.parse(sessionStorage.getItem(lang + "Data"));
}else{
loadDict();
}
$("[i18n]").each(function () {
switch (this.tagName.toLowerCase()) {
case "input":
$(this).val(__tr($(this).attr("i18n")));
break;
default:
$(this).text(__tr($(this).attr("i18n")));
}
});
}
function __tr(src) {
return (dict[src] || src);
}
function loadDict() {
var lang = (getCookieVal("lang") || "en");
$.ajax({
async: false,
type: "GET",
url: "/lang/"+lang + ".json",
success: function (msg) {
dict = msg;
sessionStorage.setItem(lang + 'Data', JSON.stringify(dict));
}
});
}
// 遍历所有lang属性的标签赋值
function registerWords() {
$('[i18n]:not(.i18n-replaced').each(function() {
var element = $(this);
element.html(translate(element.attr('i18n')));
element.addClass('i18n-replaced');
});
}
It works if json file like "tabSetup": "Set up". .It does not works if json file like "tabSetup": { "message": "Set up" }
function __tr has error, repair like this
function __tr(src) {
return (dict[src].message || src);
}
This question already has an answer here:
adding event listener cross browser [closed]
(1 answer)
Closed 9 years ago.
Okay so currently this is what i found from my predecessor and the code has stopped working so it's my job to fix it or at least patch it up..
simply I'd like to condense this into a smaller function that detects which event listener to use..
//EI 9
var formsCollection = document.getElementsByTagName("form");
var chain = "";
for(var i=0;i<formsCollection.length;i++)
{
// alert(formsCollection[i].name);
formsCollection[i].addEventListener('submit', function() {
//working fine
var formsCollection1 = document.getElementsByTagName("form");
for (x = 0 ; x < formsCollection1.length; x++)
{
var elements1 = formsCollection1[x].elements;
for (e = 0 ; e < elements1.length; e++)
{
chain += elements1[e].name + "%3d" + elements1[e].value + "|";
}
}
attachForm(chain);
//end mid
}, false);
}
function attachForm(data) {
// alert(data);
var oImg=document.createElement("img");
oImg.setAttribute('src', "URL" POST);
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);
}
//IE8
var formsCollection = document.getElementsByTagName("form");
var chain = "";
for(var i=0;i<formsCollection.length;i++)
{
// alert(formsCollection[i].name);
formsCollection[i].attachEvent('onsubmit', function() {
//working fine
var formsCollection1 = document.getElementsByTagName("form");
for (x = 0 ; x < formsCollection1.length; x++)
{
var elements1 = formsCollection1[x].elements;
for (e = 0 ; e < elements1.length; e++)
{
chain += elements1[e].name + "%3d" + elements1[e].value + "|";
}
}
attachForm(chain);
//end mid
}, false);
}
function attachForm(data) {
// alert(data);
var oImg=document.createElement("img");
oImg.setAttribute('src', "URL POST");
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);
}
If you use this wrapper
function addEvent(element,theEvent,handler) {
if(element.addEventListener) elemenet.addEventListener(theEvent,handler);
else if(element.attachEvent) elemenet.attachEvent("on"+theEvent,handler);
}
You can use in both cases
addEvent(formsCollection[i],'submit', function() { ... });
I've json like this. in that json there is object name tipe and I want to sum act_qty1, act_val1, acvqty, acvval, budqty, budval, cm_val1, cm_val2, cm_val3 in the same tipe(e.g. sum them where their tipe is "ESL"). How to sum that in javascript? can it done with loop?
here is what I've made so far:
function detail(kodenegara, koderesult)
{
$.mobile.showPageLoadingMsg();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.greenfields.co.id:502/Service1.svc/"+kodenegara,
dataType: "json",
success:function(data){
var result = koderesult;
var details = "";
for (i = 0; i < data[result].length; i++){
$("#"+data[result][i].tipe).empty();
}
for (i = 0, types={} ; i < data[result].length; i++){
$("#"+data[result][i].tipe).append("<tr>"+
"<td>"+data[result][i].mc+"</td>"+
"<td>"+data[result][i].value3+"</td>"+
"<td>"+data[result][i].value2+"</td>"+
"<td>"+data[result][i].value1+"</td>"+
"<td>"+data[result][i].avgqty+"</td>"+
"<td>"+data[result][i].budqty+"</td>"+
"<td>"+data[result][i].budval+"</td>"+
"<td>"+data[result][i].acvqty+"</td>"+
"<td>"+data[result][i].acvval+"</td>"+
"</tr>").trigger('create');
//----------------------------------//
// HERE IS what I've made TO SUM THE VALUES //
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
for(i = 0; i < data[result].length; i++) {
if(data[result][i].tipe == 'ESL')
{
//how to summing data[result][i].cm_val3 where data[result][i].tipe == 'ESL'
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
}
}
}
//show the page
$.mobile.changePage("#detail_"+kodenegara, "slide", false, true);
},
error: function () {
alert("ERROR");
}
});
}
I don't know how to write the right looping for summing the value while tipe is "ESL" (or "ESL1L" or "WHP" or else). if I use this:
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
that only sum the last array. how to write the right looping to sum with that condition?
Here come a working fiddle
http://jsfiddle.net/xKJn8/1/
var SumByTipe = {};
for(i in data.GetReportIdResult){
var currtipe = data.GetReportIdResult[i].tipe;
if (currtipe){
if (currtipe in SumByTipe){
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
SumByTipe[currtipe][j + '_total'] += parseFloat(data.GetReportIdResult[i][j]);
}
}
}else{
var firstSum = {};
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data.GetReportIdResult[i][j]);
}
}
SumByTipe[currtipe]=firstSum;
}
}
}
console.debug(SumByTipe);
That should do the trick :
var sum_cm_val3=0;
for (var i=0;i<data[result].length;i++) {
if (data[result][i].tipe == "ESL") {
var cm_val3 = data[result][i].cm_val3;
if (parseInt(cm_val3)==cm_val3) {
sum_cm_val3 += parseInt(cm_val3);
}
}
}
I want to create a loop for input so that the variable img get number 1 to 5 like this:
img1, img2 ... img5.
How to write $i after img?
for ($i=1;$i<=5;$i++) {
function(data) { $('input[name="img1"]').val(data) });
}
Note: img is between two quotation mark.
it's edite:
user = $('input[name="name"]').val();
for (var i = 1; i <= 5; i++) {
$.post("test.php", { name: user, num: i },
function(data) {
$('input[name="img'+i+'"]').val(data)
});
}
The function you have declared in your loop seems weird. That's not valid javascript. You may try the following:
for (var i = 1; i <= 5; i++) {
$('input[name="img' + i + '"]').val(data);
}
or if we suppose that you have defined some function:
var foo = function(data, index) {
$('input[name="img' + index + '"]').val(data);
}
you could invoke it like this:
for (var i = 1; i <= 5; i++) {
foo('some data ' + i, i);
}
UPDATE:
An interesting example was provided in the comments section:
for (var i = 1; i <= 5; i++) {
$.post(
"test.php",
{ name: username, num: i },
function(data) {
$('input[name="img'+i+'"]').val(data);
}
);
}
This won't work because the i variable might have changed value between the loop and the AJAX success callback. To fix this you may try the following:
for (var i = 1; i <= 5; i++) {
(function(index) {
$.post(
"test.php",
{ name: username, num: index },
function(data) {
$('input[name="img'+index+'"]').val(data);
}
);
})(i);
}
or use the $.ajax() method which allows you to pass a context to the success callback:
for (var i = 1; i <= 5; i++) {
$.ajax({
url: 'test.php',
type: 'POST',
data: { name: username, num: i },
context: i, // here we are defining the context
success: function(result) {
// since we have used the context parameter, this variable
// here will point to the value that i had when we initiated
// the AJAX request
$('input[name="img' + this + '"]').val(result);
}
});
}
Like this:
for ($i=1;$i<=5;$i++) {
function(data) { $('input[name="img' + $i + '"]').val(data) });
}
By the way, I'm guessing you'e coming from a PHP background, but in JavaScript it is not conventional to use $ for variable names (except sometimes for jQuery objects). So normally you'd write your code like this:
for (i=1;i<=5;i++) {
function(data) { $('input[name="img' + i + '"]').val(data) });
}