Loop Function Javascript - javascript

I am newbie in javascript, I want to do looping normally use "for". I would like to duplicate this script about 10 ...
how loop this script?
function getComboMotif1() {
$.get("file.php?opt1=" + $("#id1"), function (data) {
$("#asd1").html(data);
});
}
The manual Loop script like this !!
function getww1() {
$.get("file.php?opt1=" + $("#id1"), function (data) {
$("#asd1").html(data);
});
}
function getww2() {
$.get("file.php?opt1=" + $("#id2"), function (data) {
$("#asd1").html(data);
});
}
function getww3() {
$.get("file.php?opt1=" + $("#id3"), function (data) {
$("#asd1").html(data);
});
} //and further

Something like that :
function getResource(which) {
$.get('file.php?opt1=' + $('#id' + which), function (data) {
$('#asd' + which).html(data);
}
}
for (var i = 0, max = 3; i < max; i += 1) {
getResource(i);
}
But your code contains a few oddities.
$('#id1') is a jquery object, so it can't be sent to the server as a string.
If you always replace the $('#asd1').html(data) in each callback, it will get overwritten each time you get an answer from the server. That's why I made it dynamic also.

If you need it to just run through a forloop, then start at 1 in order to accommodate your name and id.
for(var i = 1; i <= 10; ++i)
$.get("file.php?opt1=" + $("#id" + i), function (data) {
$("#asd1").html(data);
});
Now since get is asynchronous, each one will not wait for the other to complete.
If you need each function to be created, getww1 and such, then I recommend using eval to create those functions for you. But, that is very inefficient to do and should be avoided unless there is a specific requirement. Ex:
...
eval("(function () { return function "
+fname+" (){"+
codeAsString
+"};})()"));
...
That will return the newly created function.
I hope this helps to some degree.

Related

Protractor - Issue in using one function value from another function

Hi I am new to protractor, I have below two functions, the first function is returning a promise, which I want to use in 2nd function to retrieve value from it and use it.
getColumnNumber(columnName) {
this.eh.waitForElement(this.GridsEleMap.get("HeaderTableHeaderRow"));
var colEle = this.GridsEleMap.get("HeaderTableHeaderRow").all(by.xpath(".//td//div[contains(#class,'text-content')]"));
return colEle.getText().then(function (text) {
var actIndex = text.indexOf(columnName) + 1;
logger.info("Column Index:" + actIndex);
});
}
clickRowElementUsingRowTextAndColumnName(rowText, columnName) {
var ele = this.GridsEleMap.get("BodyTable");
return this.getColumnNumber(columnName).then(function (result) {
logger.info("Text:" + result);
var cellEle = ele.all(by.xpath(".//tr//td[" + result + "]//div[#class='virtualLink']"));
logger.info("Result:" + cellEle);
return cellEle.filter(function (elem) {
browser.actions().mouseMove(elem).perform();
browser.sleep(50);
return elem.getText().then(function (text) {
return text.trim() === rowText.trim();
});
}).each(function (element) {
browser.actions().mouseMove(element).perform();
element.click();
browser.sleep(10*1000);
});
});
Whenever I am trying to use "result" object of then function applied on first function in clickRowElementUsingRowTextAndColumnName, its value is coming as undefined. Please help me with it.
I have to pass this result value to form a xpath of particular column index and perform operation on it.
You should return properly the value from the first function.
You can try the following code for example:
getColumnNumber(columnName) {
...
return colEle.getText().then(function (text) {
return text.indexOf(columnName) + 1;
});
}
If you see, it returns the actIndex.
Pay also attention that you have few code not chained properly, all protractor methods return promises which need to be chained in order to be sure to keep the flow sync.
Then, just as suggestion, try to avoid the use of xpath locators.
They are unreadable and they bring to a decrease of performances.

Cannot pass data to getJSON even with closures

I went through many solutions to this problem on SO and none of them work for me, unfortunately.
I want to dynamically load and place some elements on my page. HTML is generated by one of the scripts and the resulting template (for injecting data into it) is passed to getJSON method. I wanted to fill that template inside my callback method and then add it to the body.
The problem is getJSON function. I tried to pass panel value with closure and bind and none of them work.
init: function(panel) {
// closure
$.getJSON("scripts/getZones.php",
(function () { // closure
var p = panel;
return function(zoneData) {
if (zoneData.status == true) {
$.each(zoneData.values, function(i, item) {
console.log("Module.Control_manual: Adding zone " + item.id);
// filling panel with data here - but panel is undefined
});
} else {
// error!
console.log("Module.Control_manual: Error: " + item['message']);
}
}
})
);
}
What is wrong with my code? Thanks!
For closure, You must execute your function, then the getJSON function could get the right callback function
init: function(panel) {
// closure
$.getJSON("scripts/getZones.php",
// closure, you must execute it first, then the `getJSON` function could get the right callback function
(function() {
var p = panel;
return function(zoneData) {
if (zoneData.status == true) {
$.each(zoneData.values, function(i, item) {
console.log("Module.Control_manual: Adding zone " + item.id);
});
} else {
// error!
console.log("Module.Control_manual: Error: " + item['message']);
}
}
}());
);
}
And further more, you should only do this closure way when you want to store the panel,otherwise you can just use panel instead the callback.
or yo can using bind method, to pass a parameter to callback function like this:
function doAfterJson(panel){
var p = panel;
return function(zoneData) {
if (zoneData.status == true) {
$.each(zoneData.values, function(i, item) {
console.log("Module.Control_manual: Adding zone " + item.id);
// filling panel with data here - but panel is undefined
});
} else {
// error!
console.log("Module.Control_manual: Error: " + item['message']);
}
}
}
}
//use 'bind(scope,parameter)' to pass scope and parameter to callback function
init: function(panel) {
// closure
$.getJSON("scripts/getZones.php",doAfterJson.bind(this,panel));
}

jQuery pass argument to $.get() callback function

I am using this piece of code to retrieve some JSONs from twitch:
for (var i = 0; i < streamList.length; i++) {
$.get(baseURL + streamList[i], getStreamInfo, "json");
}
where getStreamInfo is the callback function. I would like to know if it is possible to pass the value of "i" to the callback function somehow, along with the JSON.
Yes, you can pass the default parameter that receive the data of the ajax query and then add the i var.
for (var i = 0; i < streamList.length; i++) {
$.get(baseURL + streamList[i],
function(data) { getStreamInfo(data, i) },
"json");
}
Note that you need to receive it in getStreamInfo function
Hope it helps.
You can add any variables you want to the anonymous object. Be sure those variables are not used by the get function.
For exemple, I added the variable foo to the anonymous object and used it with this.foo in the callback function :
for (var i = 0; i < streamList.length; i++) {
$.get({
url: baseURL + streamList[i],
success: getStreamInfo,
dataType: "json",
foo:i
});
}
function getStreamInfo()
{
var i = this.foo;
}
You can use Closures.
for (var i = 0; i < streamList.length; i++) {
(function(index){
$.get(baseURL + streamList[i], function(data){
getStreamInfo(data, index);
}, "json");
})(i);
}
Note: Modify your function getStreamInfo to accept index.
Read How do JavaScript closures work?

Javascript SDK: can i have another FB.api() calls inside FB.api()

// count total no. of groups created by me
function totalGroups(response) {
FB.api('/me/groups', {fields:'owner'}, function(g_response) {
for (i in g_response.data) {
FB.api('/me', function(m_response) {
var c = 0;
if (g_response.data[i].owner.name == m_response.name) {
c++;
}
});
}
console.log('Total:' +c);
});
}
hi, can i have another FB.api() calls inside FB.api() like i do on the above code because i can't get the value for if (g_response.data[i].owner.name == m_response.name)
Yes, you can embed a FB.api() call inside another Fb.api() call but the flow is guaranteed as the FB.api() calls are asynchronous.
One issue I found with your code is related to the var c.
First of all it's out of scope for console.log('Total:' +c) method and moreover you have declared it inside the loop which means it's value will be reset after each loop execution.
Try this:
// count total no. of groups created by me
function totalGroups(response) {
var c = 0;
FB.api('/me/groups', {fields:'owner'}, function(g_response) {
for (i in g_response.data) {
FB.api('/me', function(m_response) {
if (i.owner.name == m_response.name) {
c++;
}
});
}
console.log('Total:' +c);
});
}
this is how i fix the problem, i know its ugly but it's the best i can do at the moment.
function totalGroups(response) {
var c = 0;
FB.api('/me', function(m_response) {
FB.api('/me/groups', {fields:'owner'}, function(g_response) {
for (i in g_response.data) {
if (g_response.data[i].owner) {
if (g_response.data[i].owner.name == m_response.name) {
c++;
}
}
}
console.log('Total: ' + c);
});
});
}

$getJSON and for loop issue

This is to populate a table with the amount of results that are returned from the MediaWiki API query /api.php?action=query&list=querypage&qppage=BrokenRedirects. The number of results is then added to the id, for example:
// BrokenRedirects
$.getJSON('/api.php?action=query&list=querypage&qppage=BrokenRedirects&format=json', function (data) {
$('#BrokenRedirects').text(data.query.querypage.results.length);
});
But as it's being repeated another 7 times I made the arguments for qppage into an array and used a for loop to shorten overall code.
var array = ['BrokenRedirects',
'DoubleRedirects',
'Unusedcategories',
'Unusedimages',
'Wantedcategories',
'Wantedfiles',
'Wantedpages',
'Wantedtemplates'];
for (var i = 0; i < array.length; i++) {
$.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
$('#' + array[i]).text(data.query.querypage.results.length);
});
}
The first, unlooped, version works. But when I added a loop it didn't. The $getJSON part executes, but it then fails to add the resultant data to the id. I ran it through JSLint which apart from complaining about functions in a loop and declaring var i with var array returned little help. I'm relatively inexperienced with javascript so thought perhaps a variable can't be used twice within a loop? Other than that, maybe something to do with using an id within a loop?
That's a classical problem : i has the value of end of loop when the callback is called.
You can fix it like this :
for (var i = 0; i < array.length; i++) {
(function(i) { // protects i in an immediately called function
$.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
$('#' + array[i]).text(data.query.querypage.results.length);
});
})(i);
}
2018 addendum:
There's now another cleaner solution in today's browsers: use let instead of var:
for (let i = 0; i < array.length; i++) {
$.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
$('#' + array[i]).text(data.query.querypage.results.length);
});
}
getJSON is an asynchronous ajax call
REFER: use synchronous ajax calls
Use Jquery $.each() to iterate over the array instead of a for loop.
For example:
$.each(array, function(_, value) {
var url = '/api.php?action=query&list=querypage&qppage=' + value + '&format=json';
$.getJSON(url, function (data) {
$('#' + value).text(data.query.querypage.results.length);
});
});
You should write a function like -
function callUrl(value)
{
$.getJSON('/api.php?action=query&list=querypage&qppage=' + value + '&format=json', function (data) {
$('#' + value).text(data.query.querypage.results.length);
});
}
and then call it with some timeout option like -
setTimeout('callUrl(+ array[i] +)',500); within the loop -
i.e.
for (var i = 0; i < array.length; i++) {
setTimeout('callUrl(+ array[i] +)',500);
}
Some delay for each call will be required here.

Categories

Resources