Javascript function is not working as expected - javascript

I have a function which is not working is expected.
The problem is that, I have set
if (Trim(ObjPriXMLHTTP.responseText) != 0) then it should go inside and run another function, which is not going currently when my if (Trim(ObjPriXMLHTTP.responseText) != 0) == 1.
The debugger just throws me out of the parent function.
I want that to run when value is other than 0
Below is my js function
function getCounterForCheck() {
StrPriFnName = "getCounterForCheckInward(" + document.getElementById('TxtInwardNo').value + ")";
var ObjPriXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
ObjPriXMLHTTP.open("GET", "FrmInwardXMLHTTP.aspx?para=" + StrPriFnName, false);
ObjPriXMLHTTP.send("");
if (Trim(ObjPriXMLHTTP.responseText) != 0) {
function getOtherDBInward() {
StrPriFnName = "FunGetOTHERDBInward(" + document.getElementById('TxtInwardNo').value + ")";
var ObjPriXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
ObjPriXMLHTTP.open("GET", "FrmInwardXMLHTTP.aspx?para=" + StrPriFnName, false);
ObjPriXMLHTTP.send("");
if (Trim(ObjPriXMLHTTP.responseText) != "") {
var StrPriData = ObjPriXMLHTTP.responseText.split('~');
document.getElementById('HidRefMkey').value = StrPriData[0];
document.getElementById('TxtDeliveredBy').value = StrPriData[1];
document.getElementById('cmbRecdDept').value = StrPriData[2];
FunEmpFillDept();
document.getElementById('cmbRecdEmp').value = StrPriData[3];
document.getElementById('HidCurrentEmp').value = StrPriData[3];
document.getElementById('Txt_RefBillNo').value = StrPriData[6];
igdrp_getComboById("DtmInfRef_DocDate").setValue(Trim(StrPriData[7]));
igedit_getById("TxtWN_Billamt").setValue(StrPriData[8]);
document.getElementById('TxtRemarks').value = StrPriData[9];
document.getElementById('TxtPartyName').value = StrPriData[10];
}
else {
alert("ERROR: Document does not exist");
//alert("ERROR: Document does not exist and status also");
document.getElementById('TxtInwardNo').focus();
return false;
}
}
}
else {
//alert('invoice not found');
}
}

There are a couple of issues with that code.
Until ES2015, it was invalid to declare a function inside a flow-control block (like the body of an if), and it remains a Really Bad Idea™. But that's what your code is doing.
You've declared the function, but you haven't called it. So stepping right out is exactly what the debugger should do; there was nothing left to do in getCounterForCheck.
In comments, you've said Trim(ObjPriXMLHTTP.responseText) will return "1" or "0" (e.g., strings). But you're comparing that to 0 (the number). Since you're using loose comparison (!=), JavaScript will coerce the value for you, and in this particular case it will do so in the way you're probably expecting. I raise it just because it might make sense for Trim to explicitly convert the value and return 1 or 0 (e.g., as numbers).
Declare the function outside the if block, and call it if you want to call it. Something like:
function getCounterForCheck() {
StrPriFnName = "getCounterForCheckInward(" + document.getElementById('TxtInwardNo').value + ")";
var ObjPriXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
ObjPriXMLHTTP.open("GET", "FrmInwardXMLHTTP.aspx?para=" + StrPriFnName, false);
ObjPriXMLHTTP.send("");
if (Trim(ObjPriXMLHTTP.responseText) != 0) {
getOtherDBInward();
}
else {
//alert('invoice not found');
}
function getOtherDBInward() {
StrPriFnName = "FunGetOTHERDBInward(" + document.getElementById('TxtInwardNo').value + ")";
var ObjPriXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
ObjPriXMLHTTP.open("GET", "FrmInwardXMLHTTP.aspx?para=" + StrPriFnName, false);
ObjPriXMLHTTP.send("");
if (Trim(ObjPriXMLHTTP.responseText) != "") {
var StrPriData = ObjPriXMLHTTP.responseText.split('~');
document.getElementById('HidRefMkey').value = StrPriData[0];
document.getElementById('TxtDeliveredBy').value = StrPriData[1];
document.getElementById('cmbRecdDept').value = StrPriData[2];
FunEmpFillDept();
document.getElementById('cmbRecdEmp').value = StrPriData[3];
document.getElementById('HidCurrentEmp').value = StrPriData[3];
document.getElementById('Txt_RefBillNo').value = StrPriData[6];
igdrp_getComboById("DtmInfRef_DocDate").setValue(Trim(StrPriData[7]));
igedit_getById("TxtWN_Billamt").setValue(StrPriData[8]);
document.getElementById('TxtRemarks').value = StrPriData[9];
document.getElementById('TxtPartyName').value = StrPriData[10];
}
else {
alert("ERROR: Document does not exist");
//alert("ERROR: Document does not exist and status also");
document.getElementById('TxtInwardNo').focus();
return false;
}
}
}
I haven't looked closely at the function, but if it doesn't have to be nested inside getCounterForCheck, you might move it out.

Related

How does JS code execution can be blocked by client?

I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.

Trying to set dynamic JS variables in a function globally

I'm trying to set local storage values using dynamic variables from within a function what will be looped through. Basically i'm just trying to do this (which works but isn't dynamic):
localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
using this:
counterMarkers[numberID] = maxMarkers[numberID];
but it's not affecting 'localStorage.lvlZeroValue' at a global level
$('#spellCountTackMax').click(function() {
var counterMarkers = [
localStorage.lvlZeroValue,
localStorage.lvlOneValue,
localStorage.lvlTwoValue,
localStorage.lvlThreeValue,
localStorage.lvlFourValue,
localStorage.lvlFiveValue,
localStorage.lvlSixValue,
localStorage.lvlSevenValue,
localStorage.lvlEightValue,
localStorage.lvlNineValue
];
var maxMarkers = [
localStorage.lvlZeroMaxValue,
localStorage.lvlOneMaxValue,
localStorage.lvlTwoMaxValue,
localStorage.lvlThreeMaxValue,
localStorage.lvlFourMaxValue,
localStorage.lvlFiveMaxValue,
localStorage.lvlSixMaxValue,
localStorage.lvlSevenMaxValue,
localStorage.lvlEightMaxValue,
localStorage.lvlNineMaxValue
];
jQuery.fn.onTackSet = function(numberID){
return this.each(function(){
if(maxMarkers[numberID] == "" || maxMarkers[numberID] == null || maxMarkers[numberID] == 0 ) {
alert("not else ran");
$(this).attr('value', "0");
$('#spin' + numberID).attr('value', "0");
counterMarkers[numberID] = "0";
maxMarkers[numberID] = "0";
} else {
alert("else ran");
$(this).attr('value', maxMarkers[numberID]);
$(this).attr('max', maxMarkers[numberID]);
// localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
alert(counterMarkers[numberID]);
alert(maxMarkers[numberID]);
// this works but isn't dynamic
localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
// my attempt at making it dynamic doesn't seem to work globally
counterMarkers[numberID] = maxMarkers[numberID];
}
});
};
$("#spin0").onTackSet(0);
So i'm pretty sure my issue is scope, yet i can't seem to get it right. Please, help. Thanks!
Do you need to keep the keys for your storage values the way you have them? If you could change them from lvlZeroValue to lvl0Value you could use the approach below:
jQuery.fn.onTackSet = function(numberID){
return this.each(function(){
if(localStorage['lvl'+numberID+'MaxValue'] == "" || localStorage['lvl'+numberID+'MaxValue'] == null || localStorage['lvl'+numberID+'MaxValue'] == 0 ) {
alert("not else ran");
$(this).attr('value', "0");
$('#spin' + numberID).attr('value', "0");
localStorage['lvl'+numberID+'Value'] = "0";
localStorage['lvl'+numberID+'MaxValue'] = "0";
} else {
alert("else ran");
$(this).attr('value', localStorage['lvl'+numberID+'MaxValue']);
$(this).attr('max', localStorage['lvl'+numberID+'MaxValue']);
localStorage['lvl'+numberID+'Value'] = localStorage['lvl'+numberID+'MaxValue'];
}
});
};
If you need to keep the keys you have now you still could adapt the above approach to your needs by building your arrays different:
var markers = [
'lvlZeroValue',
'lvlOneValue',
'lvlTwoValue',
'lvlThreeValue',
'lvlFourValue',
'lvlFiveValue',
'lvlSixValue',
'lvlSevenValue',
'lvlEightValue',
'lvlNineValue'
];
var maxMarkers = [
'lvlZeroMaxValue',
'lvlOneMaxValue',
'lvlTwoMaxValue',
'lvlThreeMaxValue',
'lvlFourMaxValue',
'lvlFiveMaxValue',
'lvlSixMaxValue',
'lvlSevenMaxValue',
'lvlEightMaxValue',
'lvlNineMaxValue'
];
and use them like this:
localStorage[markers[numberID]] = localStorage[maxMarkers[numberID]];
Here is a fiddle to see how it works.
i think i fixed it doing this:
jQuery.fn.onTackSet = function(countLocation, numberID){
return this.each(function(){
if(maxMarkers[numberID] == "" || maxMarkers[numberID] == null || maxMarkers[numberID] == 0 ) {
// alert("not else ran");
$(this).attr('value', "0");
$('#spin' + numberID).attr('value', "0");
counterMarkers[numberID] = "0";
maxMarkers[numberID] = "0";
} else {
// alert("else ran");
$(this).attr('value', maxMarkers[numberID]);
$(this).attr('max', maxMarkers[numberID]);
// localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
alert(countLocation);
alert(maxMarkers[numberID]);
// this works but isn't dynamic
// localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
localStorage.setItem(countLocation, maxMarkers[numberID]);
// my attempt at making it dynamic doesn't seem to work globally
// counterMarkers[numberID] = maxMarkers[numberID];
}
});
};
$("#spin0").onTackSet("lvlZeroValue", 0);
...but your answer is cleaner. Thanks a lot for your input. I will try it your way. Actually i still need to update the if null, if "" section of this...

javascript variable showing as undefined in Elevator Saga learning tool

I'm new to JavaScript, coming over from Swift. Trying it out code-learning challenges at http://play.elevatorsaga.com/
and some behavior is tough to grasp. In the following code, I setup floor & elevator objects. I am trying to get the elevator to get the floor it is about to pass's button request (if someone has pressed that floor's up or down button to call the elevator)
- in the code console.log(" (x) passing_floor - Same direction requested");
However the logs I get tell me that the up/downRequests are undefined
passing_floor 2 up
upRequest: undefined
downRequest: undefined
Is the issue with initialization? scoping? What is the proper way to achieve what I am trying to do?
{
init: function(elevators, floors) {
function initializeElevator(elevator){
elevator.on("floor_button_pressed", function(floorNum) {
elevator.goToFloor(floorNum);
});
elevator.on("idle", function() {
elevator.goToFloor(0);
});
elevator.on("passing_floor", function(floorNum, direction) {
if ((floorNum.upRequest) && (direction =='up')) {
floorNum.upRequest = false;
console.log(" (x) passing_floor - Same direction requested");
} else if ((floorNum.downRequest) && (direction == 'down')) {
floorNum.downRequest = false;
console.log(" (x) passing_floor - Same direction requested");
} else {
console.log("passing_floor " + floorNum + " " + direction);
console.log("upRequest: " + floorNum.upRequest);
console.log("downRequest: " + floorNum.downRequest);
}
});
}
function initializeFloor(floor){
var upRequest = false;
var downRequest = false;
floor.on("up_button_pressed", function() {
this.upRequest = true;
});
floor.on("down_button_pressed", function() {
this.downRequest = true;
});
}
elevators.forEach(initializeElevator);
floors.forEach(initializeFloor);
},
update: function(dt, elevators, floors) { }
}
Thank you for taking the time to help me understand Javascript a bit more, trying out W3School to get around it, but let me know if you have better sites I should look at..
I was able to proceed with the desired behavior by creating an "array" of floors that were global - I'm not sure if this was a scoping issue or something else though!
{
init: function(elevators, floors) {
var floorArray = new Array(floors.length);
var elevatorOnFloor = new Array(floors.length);
//the init function populates the listeners for the elevator objects
function initializeElevator(elevator){
elevator.on("floor_button_pressed", function(floorNum) {
elevator.goToFloor(floorNum, true);
});
elevator.on("idle", function() {
elevator.goToFloor(0);
});
elevator.on("passing_floor", function(floorNum, direction) {
if ((floorArray[floorNum] == 1) && (direction =='up')) {
floorArray[floorNum] = 0;
elevator.goToFloor(floorNum, true);
console.log("picking someone else going UP");
elevatorOnFloor[floorNum]+=1;
console.log("elevators per floor:"+ elevatorOnFloor );
} else if ((floorArray[floorNum] = 2) && (direction == 'down')) {
floorArray[floorNum] = 0;
elevator.goToFloor(floorNum, true);
console.log("picking someone else going DOWN");
elevatorOnFloor[floorNum]-=1;
console.log("elevators per floor:" + elevatorOnFloor + floorArray );
} else {
console.log("passing_floor " + floorNum + " " + direction);
if (direction =='up') {
elevatorOnFloor[floorNum]+=1;
} else {
elevatorOnFloor[floorNum]-=1;
}
}
});
}
function initializeFloor(floor){
floor.on("up_button_pressed", function() {
floorArray[floor] = 1;
});
floor.on("down_button_pressed", function() {
floorArray[floor] = 2;
});
}
function initializeElevatorsOnFloor(floor){
elevatorOnFloor[floor] = 0;
}
// we initialize all the elevators
elevators.forEach(initializeElevator);
// initialize the floors
floors.forEach(initializeFloor);
floors.forEach(initializeElevatorsOnFloor);
},
update: function(dt, elevators, floors) {
// We normally don't need to do anything here
}
}

Unexpected } tokens in js - trying to learn ajax

I'm just trying to learn some ajax so I wrote some code for basically an address book to pull some data. My javascript is rubbish but I cannot seem to understand what I am doing wrong, the error points to function ajaxCall but I see no issue with that function either:
(function () {
var searchForm = document.getElementById("search-form"),
searchField = document.getElementById("q"),
getAllButton = document.getElementById("get-all"),
target = document.getElementById("output");
var addr = {
search: function (event) {
var output = document.getElementById("output");
//start ajax call
ajaxCall("data/contacts.json", output, function (data) {
var searchValue = searchField.value,
addrBook = data.addressBook,
count = addrBook.length,
i;
//stop default behavior
event.preventDefault();
//clear target
target.innerHTML = "";
if (count > 0 && searchValue !== "") {
for (i = 0; i < count; i++) {
var obj = addrBook[i],
isItFound = obj.name.indexOf(searchValue);
if (isItFound !== -1) {
target.innerHTML += '<p>' + obj.name + ', ' + obj.email + '<p>';
} //end if isItFound
} //end for loop
} //end if count check
}); //end ajax call
}, //end method search
getAllContacts: function () {
var output = document.getElementById("output");
ajaxCall("data/contacts.json", output, function (data) {
var addrBook = data.addressBook,
count = addrBook.length,
i;
target.innerHTML = "";
if (count > 0) {
for (i = 0; i < count; i++) {
var obj = addrBook[i];
target.innerHTML += '<p>' + obj.name + ', ' + obj.email + '<p>';
} //end for loop
} //end if
}); //end ajax call
}, //end method getAllContacts
setActiveSection: function () {
this.parentNode.setAttribute("class", "active");
}, //end method setActiveSection
removeActiveSection: function () {
this.parentNode.removeAttribute("class");
}, //end method removeActiveSection
addHoverClass: function () {
searchForm.setAttribute("class", "hovering");
}, //end method addHoverClass
removeHoverClass: function () {
searchForm.removeAttribute("class");
} //end method removeHoverClass
} //end addr object
searchField.addEventListener("keyup", addr.search, false);
searchField.addEventListener("focus", addr.addActiveSection, false);
searchField.addEventListener("blur", addr.removeActiveSection, false);
getAllButton.addEventListener("click", addr.getAllContacts, false);
searchForm.addEventListener("submit", addr.search, false);
searchForm.addEventListener("mouseover", addr.addHoverClass, false);
searchForm.addEventListener("mouseout", addr.removeHoverClass, false);
})(); //end anon function
function getHTTPObject() {
var xhr;
//in most cases this first if is executed
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
//otherwise support crappy IE6 and below
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
return xhr;
}
function ajaxCall(dataUrl, outputElement, callback) {
//get ajax object
var request = getHTTPObject();
outputElement.innerHTML = "Loading...";
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
//good ajax response..now save it
var contacts = JSON.parse(request.responseText);
if (typeof callback === "function")
callback(contacts);
} //end upper if
} //end onreadystatechange
request.open("GET", dataUrl, true);
request.send(null);
}
The javascript development tools keeps giving me an unexpected token } on line 97 but that changes all so often. Am I missing a curly brace somewhere?
I did put your code to this fiddle and fixed the errors as far as i can.
You missed some curly braces and semicolons. Also, you used ajaxCall() and getHTTPObject() before they were declared. Check it out. Unfortunately, i dont know if the problem is already fixed, but now the code is valid at least :)
Btw: (in my opinion) such long Code-Samples are always better pasted into a fiddle. Not only because you can focus on the probably messy code here while referring to the complete code sample somewhere else, also because you can make sure that there are no syntax-errors as you can quickly validate you code using jsLint before asking the question here.
You must re-check what your JSON response is, in console, and see if it is invalid.
Because at that very 97 line you say that you are parsing a response.

Javascript, problem with binding an event to a div-tag

i am trying to bind an event to a dynamically created div.
function GameField(playerNumber) {
this.fields = new Array();
this.player = playerNumber;
this.isPlayerActive = false;
this.currentRound = 0;
}
GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
if (fieldNumber == 0 || fieldNumber == 6 || fieldNumber == 8 || fieldNumber == 17)
newField.className = 'gameCellSmall borderFull gameText gameTextAlign';
else
newField.className = 'gameCellSmall borderWithoutTop gameText gameTextAlign';
newField.onclick = function() { this.DivClick('a'); }
this.fields[fieldNumber] = newField;
return newField;
}
GameField.prototype.DivClick = function(fieldNumber) {
alert('Nummer: ' + fieldNumber);
}
Everything works perfectly, but when you click on one of the created divs, i end up with the following error message: Error: Object doesn't support this property or method.
If i replace the onclick function with this, then it works:
newField.onclick = function() { alert('Nummer: ' + fieldNumber); }
How can i get the onclick event to fire my DivClick function instead?
The problem is that the onclick event handler gets executed with the this value pointing to the DOM element that triggered the event, so that's why executing this.DivClick fails.
You need to enforce the context, in order to use instance methods within the event handler, for example, you could store a reference to the current instance:
GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
//...
var instance = this;
newField.onclick = function() { instance.DivClick('a'); }
//...
}
That is the way
function DivClick (fieldNumber) {
alert('Nummer: ' + fieldNumber);
}
{ this.DivClick('a'); } - should be replaced to { DivClick('a'); }

Categories