jQuery AJAX method is calling onchange of objects - javascript

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?

Related

can't send value to database postgresql with Django and javascript

i'm try use Ajax send correctAnswers to postgresql with Django but it error.
I don't know where I missed it.
function checkAnswers() {
window.scrollTo(0, 0);
var correctAnswers = 0;
for (var i = 0; i < questions.length; i++) {
var radios = document.getElementsByName("question" + (i + 1));
var questionCol = document.getElementsByClassName("col-12")[i];
var isCorrect = false;
for (var j = 0; j < radios.length; j++) {
if (radios[j].value == questions[i].correctAnswer && radios[j].checked) {
correctAnswers++;
isCorrect = true;
break;
}
}
document.getElementById("result").innerHTML =
"คุณได้คะแนน " + correctAnswers + " / " + questions.length;
var backButton = document.createElement("input");
backButton.setAttribute("type", "button");
backButton.setAttribute("value", "กลับไปหน้าหลัก");
backButton.setAttribute("class", "btn btn-primary center1");
backButton.setAttribute("onclick", "location.href='User-page.html'");
document.getElementById("quizForm").appendChild(backButton);
$.ajax({
url: "/submit_quiz/",
type: "POST",
data: { correctAnswers: correctAnswers },
success: function (response) {
console.log("ส่งค่าไป data base สำเร็จ");
},
});
}
It has no ajax response.

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;
}

Passing JSON parse value to a global variable

$(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);
});
}

confusing javascript setinterval, loop and jquery ajax load priorities

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);
}

Categories

Resources