I am trying to dynamically populate the jquery chosen plugin both with "optgroup" and "option". I therefore have nested ajax requests and forloops:
$.ajax({
url: '#Html.Raw(Url.Action("GetCat", "MController"))',
data: { ID: metada },
success: function (data) {
var categories = data.split(",");
for (i = 0; i < categories.length; i++) {
$.ajax({
url: '#Html.Raw(Url.Action("GetCat", "MController"))',
data: { ID: cetada },
success: function (data) {
$("#picker").append("<optgroup label='" + categories[i] + "'>");
var subcategories = data.split(",");
for (i = 0; i < subcategories.length; i++) {
$("#picker").append("<option value='"+subcategories[i]+"'>" + subcategories[i] + "</option>")
}
$("#picker").append("</optgroup>");
}
});
}
$("#picker").trigger('chosen:updated');
}
});
Currently when I run the above the chosen select is empty and no options or optgroups are visible.
I think you need to use promises for this:
var promises = [];
for (var i = 0; i < categories.length; i++) {
promises.push(
(function(innerI){
return $.ajax({
url: '#Html.Raw(Url.Action("GetCat", "MController"))',
data: { ID: cetada },
success: function (data) {
var optgroup = $('<optgroup>').attr('label', categories[innerI]);
var subcategories = data.split(",");
for (var i = 0; i < subcategories.length; i++) {
var option = $('<option>').val(subcategories[i]).text(subcategories[i]);
optgroup.append(option);
}
$("#picker").append(optgroup);
}
});
})(i)); // unbind i to make closure work.
}
$.when.apply($, promises).then(function() {
$("#picker").trigger('chosen:updated');
});
UPDATE1:
I missed closures on first look, now th code is updated.
UPDATE2:
Rewrote working with tags inside success callback of ajax request.
UPDATE3:
Here is simple demo, I've commented some non-important code to show how it works.
Related
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: 'https://reqres.in/api/users?page=1',
method: 'GET',
success: function(result) {
console.log(i); // 0
requests[i].apply(undefined, []);
}
});
});
console.log(i); //counts up
})(i, data);
};
requests[0].apply(undefined,[]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am wondering, how come with this code:
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: wpApiSettings.root + 'superdooperendpoint/' + apikey + "/" + data[i].start_date + "/" + data[i].end_date,
method: 'GET',
beforeSend: function(xhr) {
// Set nonce here
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
},
success: function(result) {
success_callback({
start_date: data[i].start_date,
end_date: data[i].end_date,
span: data[i].span,
result: result
});
console.log(i); // 0
requests[i].apply(undefined, []);
}
});
});
console.log(i); //counts up
})(i, data);
};
When I do the first console.log() in the success function it is always 0, not undefined, yet while outside of the success function it counts up in the iterating for loop. How can I get it to count up in the success function as well?
The following paints the updated value of i
Parallel Calls
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: 'https://reqres.in/api/users?page=1',
method: 'GET',
success: function(result) {
console.log(i);
}
});
});
})(i, data);
};
for (var i = 0; i < requests.length; i++) {
requests[i].apply(undefined, []);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Sequential Calls
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: 'https://reqres.in/api/users?page=1',
method: 'GET',
success: function(result) {
console.log(i);
i++;
if(i < requests.length) {
requests[i].apply(undefined, []);
}
}
});
});
})(i, data);
};
requests[0].apply(undefined, []);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Explanation - When you iterated over the function, for each function in requests array a value of i was passed/stored just like an argument. When you invoke the requests[0] from outside, on completion of the function, the stored value of i i.e. 0 is painted. And then, you again trigger the function stored at index = 0 i.e. you end up creating an infinite loop. In order to paint the appropriate value, loop over the requestsarray and call the individual function one by one to see the appropriate value of i being logged.
You need to assign i to a different local variable of the nested function and put the definition of i out of the block;
let i = 0;
for (; i < 100; i++) {
((n) => new Promise(
(res, rej) => setTimeout(res, 100)
).then(() => console.log(i,n))
)(i);
}
I'm looking to dynamically add properties and values to my ajax parameters, does anybody know how to do this? I can't seem to figure out how to accomplish this task. Thanks
doLookup = function($field, url, query, process, filterIdArray) {
$field.addClass("ajax-wait");
return ajax(url, {
parameters: {
"t:input": query,
"t:inputFilter": $filterField.val(),
for (var i = 0; i < filterIdArray.length; i++) {
"t:inputFilter_" + i : $("#" + myStringArray[i]);
},
},
success: function(response) {
$field.removeClass("ajax-wait");
return process(response.json.matches);
}
});
};
Create parameters outside the ajax function like:
params = {};
params["t:input"] = query;
params["t:inputFilter"] = $filterField.val();
for (var i = 0; i < filterIdArray.length; i++) {
params["t:inputFilter_" + i] = $("#" + myStringArray[i]);
}
return ajax(url, {
parameters: params,
success: function(response) {
$field.removeClass("ajax-wait");
return process(response.json.matches);
}
});
};
In the code below, I assign a value to a variable from JSON with this var tag = data[j]['text']; and I output it with this console.log(tag); (for testing) which works.
I try to push the values into an array with tags.push(tag); but it WILL NOT WORK!
Why won't these values go into the array? I am just trying to get the contents of tag into an array...
function GetAvailableTags() {
var url = '/TextCodes/TextCodes?key=';
var tagGroups = [];
$('.ui-autocomplete-input').each(function () {
var key = $(this).attr('id');
var tags = [];
//console.log(key);
$.getJSON(url + key, function (data) {
for (var j = 0, len = data.length; j < len; j++) {
var tag = data[j]['text'];
console.log(tag);
tags.push(tag);
}
});
console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
console.log(tags[k]);
}
});
}
Thanks for your help.
Because $.getJSON is an asynchronous function. It means that your code
console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
console.log(tags[k]);
}
will be executed before the $.getJSON callback function :
function () {
var key = $(this).attr('id');
var tags = [];
//console.log(key);
$.getJSON(url + key, function (data) {
for (var j = 0, len = data.length; j < len; j++) {
var tag = data[j]['text'];
console.log(tag);
tags.push(tag);
}
}
It is why your variable seems to be empty when look into in your code above, but how it is possible that the data are printed with console.log(tag); in the callback function.
Update
Here is an example of using $.ajax method instead of $.getJSON to specify that the data must be retrieved synchronously using the parameter asynch : false
By that way, the server call response (success callback) is mandatory to continue the process. The disadvantage of this non-standard way is that your web page could be freezed waiting the server response. It is not the best elegant way to do that, but sometimes it is useful.
function GetAvailableTags() {
var url = '/TextCodes/TextCodes?key=';
var tagGroups = [];
$('.ui-autocomplete-input').each(function () {
var key = $(this).attr('id');
var tags = [];
//console.log(key);
$.ajax({
url: url + key,
type: 'POST',
asynch: false,//specify to stop JS execution waiting the server response
success: function (data) {
for (var j = 0, len = data.length; j < len; j++) {
var tag = data[j]['text'];
console.log(tag);
tags.push(tag);
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert('an error occurred!');
}
});
console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
console.log(tags[k]);
}
});
}
My solution is kind of long and stupid, but it works. Now, I can access the variables like an array textCodes['taxes']. sdespont's async note helped, too.
var textCodes = GenerateTextCodes();
console.log(textCodes);
function GenerateTextCodes() {
var arr = [];
$('.ui-autocomplete-input').each(function () {
var id = $(this).attr('id');
arr[id] = GetAvailableTags(id);
});
//console.log(arr['taxes']);
return arr;
}
// get all autocomplete element IDs and put them into an array
function GetAvailableTags(key) {
var url = '/TextCodes/TextCodes?key=';
var tags = [];
$.ajax({
url: url + key,
type: 'GET',
async: false,
success: function (data) {
//console.log(data[0].text);
//console.log(data.length);
for (var i = 0; i < data.length; i++) {
//console.log(data[i].text);
tags.push(data[i].text);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('an error occurred!');
}
});
//console.log(tags);
return tags;
}
straight to the point
i have the following javascript and jquery code which update some checked rowsand do some stuff on each datatables row. here is my code:
function checkUpdate(){
setInterval(function(){
var listLength = updateList.length;
if(listLength > 0){
for(var r=0; r<listLength; r++){
// console.log(r)
var clID = updateList[r];
// console.log(clID)
var rRow = $('#dataTable tbody tr').find('td[data-clientid="'+clID+'"]').parent('tr');
// console.log(rRow)
var rRowIndex = rRow.index();
// console.log(rRowIndex)
var rRowDataIndex = oTable.fnGetPosition(rRow[0]);
console.log(rRowDataIndex)
$.ajax({
url: '/cgi-bin/if-Clients-list.jpl',
data: 'session=' + recievedSession + '&clientid=' + clID + '&outputformat=json',
dataType: 'json',
success: function(rowData){
// console.log(rowData)
var newRow = [];
var newOrderedRow = [];
console.log(rRowDataIndex)
newRow.push(rRowDataIndex+1, "");
for (var title in rowData[0]){
newRow.push(rowData[0][title]);
}
console.log(newRow)
},
});
};
}
},2000)
};
here is the problem:
after $.ajax() call, rRowDataIndex variable does not update or it updates but there is a problem in scopes and priorities that i couldn't understand
if i check 2 rows or more all the console.log(newRow)'s first elements will be the same
can anyone help me?
PS. i can nor present any code on web
thanks every body
You need to wrap the AJAX call in a closure to capture the value of rRowDataIndex each time through the loop.
function checkUpdate() {
setInterval(function () {
var listLength = updateList.length;
if (listLength > 0) {
for (var r = 0; r < listLength; r++) {
// console.log(r)
var clID = updateList[r];
// console.log(clID)
var rRow = $('#dataTable tbody tr').find('td[data-clientid="' + clID + '"]').parent('tr');
// console.log(rRow)
var rRowIndex = rRow.index();
// console.log(rRowIndex)
var rRowDataIndex = oTable.fnGetPosition(rRow[0]);
console.log(rRowDataIndex)
(function (rRowDataIndex) {
$.ajax({
url: '/cgi-bin/if-Clients-list.jpl',
data: 'session=' + recievedSession + '&clientid=' + clID + '&outputformat=json',
dataType: 'json',
success: function (rowData) {
// console.log(rowData)
var newRow = [];
var newOrderedRow = [];
console.log(rRowDataIndex)
newRow.push(rRowDataIndex + 1, "");
for (var title in rowData[0]) {
newRow.push(rowData[0][title]);
}
console.log(newRow)
},
});
})(rRowDataIndex);
};
}
}, 2000);
}
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) });
}