Passing JSON parse value to a global variable - javascript

$(function() {
var global_datalength = 0;
leavereminder();
alert(global_datalength);
});
function leavereminder() {
$.getJSON("<?=base_url()?>home/leavereminder",
{},
function(data) {
if(data.length != 0) {
for(x=0; x<data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>'+data[x]+'</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
var datalength = data.length;
});
global_datalength = datalength;
}
I have a global variable of global_datalength and i want to replace it with my return json
but when i alert my code it always 0. it didnt pass my global_datalength = datalength. because when outside of json function my data.length is unknown

Remove the var keyword on global_datalength to make it global.
You can also use window.global_datalength.
Another way is to declare the variable outside the jQuery ready function.
Your JSON call is async. That means the alert will be called before the JSON has returned from the server.
What you can do is:
function leavereminder() {
$.ajax({
dataType: "json",
url: "<?=base_url()?>home/leavereminder",
async: false,
success: function(data) {
if(data.length != 0) {
for(x=0; x<data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>'+data[x]+'</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
global_datalength = datalength;
},
});
}

Need to keep global_datalength outside the jQuery function.
Also since leavereminder is asynchronous, you might want to keep global_datalength = datalength; inside the function(data)
var global_datalength = 0;
$(function () {
leavereminder();
});
function leavereminder() {
$.getJSON("<?=base_url()?>home/leavereminder", {},
function (data) {
if (data.length != 0) {
for (x = 0; x < data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>' + data[x] + '</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
global_datalength = data.length;
alert(global_datalength);
});
}

Related

making multiple ajax calls within a for loop

I'm a relative newbie to javascript and I'm trying to make multiple ajax calls within a for loop. It loops through the elements of an array using a different url for an ajax call each time it goes through the loop. The problem is that the value of the variable 'test' is always equal to "condition4". I'm used to other languages where the value of 'test' would be "condition1", then "condition2" etc as it goes through the for loop. Here is a simplified version of my code:
var myData = [];
var cnt = 0;
var link;
var myCounter = 0;
var myArray = ["condition1", "condition2", "condition3", "condition4"];
for (x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
GetJSON(function (results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = myArray[myCounter];
myData[cnt] = { "id": id, "test": test };
cnt++;
}
});
}
function GetJSON(callback) {
$.ajax({
url: link,
type: 'GET',
dataType: 'json',
success: function (results) {
callback(results);
}
});
}
I think you can solve this issue by sending and receiving myCounter value to server
for (x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
$.ajax({
url: link,
type: 'GET',
dataType: 'json',
data: { myCounter: myCounter}
success: function(results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = results.data[i].myCounter
myData[cnt] = {
"id": id,
"test": test
};
cnt++;
}
}
});
}
When you are executing the loop, it attaches the myCounter reference. Then, due to the async task, when it finishes and call 'myCounter', it has already achieved the number 4. So, when it call 'myCounter', it is 4. To isolate the scope, you need to create a new scope every iteration and isolating each value of 'myCounter'
for (x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
//IIFE
(function() {
var ownCounter = myCounter; //Isolating counter
GetJSON(function (results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = myArray[ownCounter];
myData[cnt] = { "id": id, "test": test };
cnt++;
}
});
})();
}
Or...
for (let x = 0; x < myArray.length; x++) {
link = "https://test.com/" + myArray[x];
myCounter = x;
GetJSON(function (results) {
for (i = 0; i < results.data.length; i++) {
var id = results.data[i].identifier;
var test = myArray[x];
myData[cnt] = { "id": id, "test": test };
cnt++;
}
});
}

Can not push an array as a property of a two dimensional empty array

$('#createFields').click(function () {
for (var i = 0; i <= numberOfFields; i++) {
fieldsArray[i] = {};
console.log(fieldsArray);
};
});
i get the numberOfFields variable from a select box
$("body").on("change","input:checkbox",
function () {
if ($(this).prop('checked')) {
var val = $(this).prop('value');
addColumns(val);
}
else {
console.log("deleting...")
singleArray=singleArray.splice(singleArray.length, newArray.length);
InitData();
}
}
);
I call the addColumns function each time a checkbox is checked.
function addColumns(val) {
var defer = $.Deferred();
newArray = [];
str = [];
str.push(val);
var url = ListJoin.appweburl + "/_api/SP.AppContextSite(#target)/Web/Lists/getbytitle('" + selectedList + "')/items?$select=" + str + "" +
"&#target='" + ListJoin.hostweburl + "'";
ListJoin.executor.executeAsync({
url: url,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
var jsonObject = JSON.parse(data.body);
var response = jsonObject.d.results;
for (var i = 0, len = response.length; i < len; i++) {
var tu = [];
var keys = Object.keys(response[i]);
//Skip keys[0] because it's always metadata
for (var j = 1; j < keys.length; j++) {
var key = keys[j];
var val = [response[i][key]];
console.log("bujar" + val);
newArray.push(val);
}
}
fieldsArray[1].push(newArray);
can not push neither concat newArray=['BBB','MMM','CCC'] to the an array of the fieldsArray array
InitData();
defer.resolve();
},
error: function (data) {
console.log(data);
defer.reject();
}
});
return defer;
}

How do I set unique value for each button to identify them?

Javascript Code:
function createdivs()
{
var i = 1;
$.ajax({ url: 'displaycontent.php',
data: {action:'test'},
type: 'post',
datatype: 'json',
success: function(output) {
var a = JSON.parse(output);
var b = a.length;
var i;
for (i = 0; i < b;i++){
console.log(a[i]['idi']);
console.log(a[i]['pgmname']);
console.log(a[i]['comp']);
console.log(a[i]['datephp']);
if (a[i]['idi'] != 0){
for (var j=0 ;j < 1;j++)
{
var editp = document.createElement("button","span");
document.getElementById('contentdisplay'+i).appendChild(editp);
editp.className = "glyphicon glyphicon-pencil";
editp.id = "editprogramsbutton"+i;
$("#editprogramsbutton"+i).click(function(){
editp.value = i;
alert(i);
});
}
}
}
}
});
}
Suppose if the loop runs for 3 times, I can create three buttons with id's as editprogramsbutton0, editprogramsbutton1, editprogramsbutton2. The problem is when I alert using
$("#editprogramsbutton"+i).click(function(){
editp.value = i;
alert(i);
});
I always get the value as 3 no matter which button I press. I know that the value of 'i' is set to 3 and it'll display the last updated value whenever I press the button. I want values like "0" when I press "editprogramsbutton0", "1" when I press "editprogramsbutton1" and so on.. Can someone please explain the logic of how to do this with possible changes in the code. Thank you in advance.
This is the key, you have to define the value outside of the click function, otherwise it will update the value to the last i set. Then call either e.target.value (make sure e is defined in the function call) or this.value (as inside an event handler this refers to the element that was clicked)
editp.value = i;
editp.addEventListener('click', function(e) {
alert(e.target.value);
}, false);
In the hidden snippet below I've simplified your script and removed unnecessary lines and document calls.
function createdivs() {
$.ajax({
url: 'displaycontent.php',
data: { action: 'test' },
type: 'post',
datatype: 'json',
success: function (output) {
var a = JSON.parse(output);
var fullDisplay = document.getElementById('fulldisplay');
for (var i = 0; i < a.length; i++) {
console.log(a[i]['idi']);
console.log(a[i]['pgmname']);
console.log(a[i]['comp']);
console.log(a[i]['datephp']);
if (a[i]['idi'] != 0) {
fullDisplay.style.visibility = "visible";
var list = document.createElement("div");
list.className = "container content-rows content";
list.id = "contentdisplay" + i;
var sno = document.createElement("span");
sno.className = "col-md-1 snocontent text_center_align";
sno.id = "snocontent" + i;
sno.innerHTML = a[i]['idi'];
list.appendChild(sno);
var pgmno = document.createElement("span");
pgmno.className = "col-md-3 pgmnamecontent";
pgmno.id = "pgmnocontent" + i;
pgmno.innerHTML = a[i]['pgmname'];
list.appendChild(pgmno);
var cmpno = document.createElement("span");
cmpno.className = "col-md-3 cmpcontent";
cmpno.id = "cmpnocontent" + i;
cmpno.innerHTML = a[i]['comp'];
list.appendChild(cmpno);
var dateno = document.createElement("span");
dateno.className = "col-md-2 datecontent";
dateno.id = "datenocontent" + i;
dateno.innerHTML = a[i]['datephp'];
list.appendChild(dateno);
var addtra = document.createElement("button", "span");
addtra.className = "glyphicon glyphicon-king";
addtra.id = "addtrainersbutton" + i;
list.appendChild(addtra);
var editp = document.createElement("button", "span");
editp.className = "glyphicon glyphicon-pencil";
editp.id = "editprogramsbutton" + i;
editp.value = i;
editp.addEventListener('click', function(e) {
alert(e.target.value);
}, false);
list.appendChild(editp);
var assigntra = document.createElement("button", "span");
assigntra.className = "glyphicon glyphicon-user";
assigntra.id = "assigntrainersbutton" + i;
list.appendChild(assigntra);
var deletep = document.createElement("button", "span");
deletep.className = "glyphicon glyphicon-pencil";
deletep.id = "deleteprogrambutton" + i;
list.appendChild(deletep);
fullDisplay.appendChild(list);
}
}
}
});
}

Count the return function

How can i count or check the length of the return function
function leavereminder() {
$.getJSON("<?=base_url()?>home/leavereminder",
{},
function(data) {
if(data.length != 0) {
for(x=0; x<data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>'+data[x]+'</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
var b = data.length;
});
}
I want my variable b to be global variable so i can fetch the length
You cannot return back values from async calls. Instead you can use callbacks to know when async call is completed. In your example :
leavereminder(function(length) {
console.log(length); // This will get you your data length immediately after JSON call is completed.
});
function leavereminder(callBack) {
$.getJSON("<?=base_url()?>home/leavereminder",
{},
function(data) {
if(data.length != 0) {
for(x=0; x<data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>'+data[x]+'</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
// Instead of this : var b = data.length;
callBack(data.length); // This will send the length back(alternate for return)
});
}
Problem with using Global variables is you will never know when the call completes(unless you add an observer but why not keep it simple?)
It's not clear what you mean by "check the length of the return function," but I think you mean check the value of b. In that case, just declare b outside your callback, like this:
var b = 0;
function leavereminder() {
$.getJSON("<?=base_url()?>home/leavereminder",
{},
function(data) {
if(data.length != 0) {
for(x=0; x<data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>'+data[x]+'</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
b = data.length;
});
}
P.S. You should use a more descriptive variable name than b - this name is hard to debug and may well conflict with other scripts on the page.
If you want b to be global then you need to initialize it outside the function. Then b will accessible by leavereminder().
var b;
function leavereminder() {
$.getJSON("<?=base_url()?>home/leavereminder",
{},
function(data) {
if(data.length != 0) {
for(x=0; x<data.length; x++) {
var lblm = document.createElement('div');
lblm.innerHTML = '<label>'+data[x]+'</label>';
lblm.className = 'alert alert-info';
document.getElementById('notifbody').appendChild(lblm);
}
}
b = data.length;
});
}
Write it in hidden html input field with jquery and use it later.
In your ajax call:
$('#count_var').val(data.length);
Your html to collect the count:
<input type="hidden" name="count_var" id="count_var" />

jQuery AJAX method is calling onchange of objects

I am a little bit confused about the jQuery AJAX method, the method is calling when I change something on the screen. May there be some problem asynchronous task?
This is inside of the jQuery click function:
$("#divModularFenster").html(html).dialog({
modal: true,
buttons: {
"OK": function () {
getJSONObjektList(function (jsonObjekt) {
console.log("Callback: " + JSON.stringify(jsonObjekt));
// other code
var pj = JSON.stringify(jsonObjekt);
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pj,
dataType: "json",
processData: false,
url: "http://localhost:53658/PostDatenZumWebservice",
success: function (data) {
alert("Post erfolgreich: ");
}
});
});
}
}
});
This method should be call before I send the data to my service:
function getJSONObjektList(callback) {
var jsonObjekt = {};
jsonObjekt.ObjektId = [];
jsonObjekt.Selected = [];
doc = Qv.GetCurrentDocument();
doc.GetAllObjects(function (objects) {
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
var id = obj.id;
var caption = obj.caption;
var type = obj.type;
var my = obj.my;
//liste alle verfuegbaren Objekte auf
jsonObjekt.ObjektId.push(id);
if (type === "Statusbox") {
doc.GetObject(id, function () {
var statusboxInhalt = this.Data.Rows;
var utilJSONObjekt;
for (var j = 0; j < statusboxInhalt.length; j++) {
utilJSONObjekt = {};
utilJSONObjekt.SelectedObjektId;
utilJSONObjekt.SelectedObjektWerte = [];
var inhalt = statusboxInhalt[j];
console.log("Name: " + inhalt[0].text + " Wert: " + inhalt[2].text);
var valAr = inhalt[2].text.split(",");
for (var k = 0; k < valAr.length; k++) {
//liste alle verfuegbaren Objekte auf
utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
}
jsonObjekt.Selected.push(utilJSONObjekt);
//callback erst starten, wenn alle Elemente durchlaufen worden sind
if (j === (statusboxInhalt.length - 1)) {
callback(jsonObjekt);
}
}
});
}
}
});
}
Some ideas?

Categories

Resources