Nested Javascript functions (re: onreadystatechage) - javascript

HELP! I am having an issue w/ one of my Javascript functions that has an inner Javascript function driven by an 'onreadystatechange'.
So all I am looking to do in my main JS code is figure out the value of jsonWR.SURG.EXIST_IND when this function runs. When the INNERretval alert runs, the value is correctly outputting to 1....this is what I expect. Then right before I return the value at the end of the main surgeryScheduled() function, ENDretval is saying the value is now 0.
I am sure I am missing something fundamental here, so can someone help me.
Plus, when surgeryScheduled() function is being called, I set a variable to the return value:
var q = 0;
q=surgeryScheduled(<someID>);
alert("q:"+q);
The above alert returns 1 when I would expect it to return 0 since ENDretval above was 0. What am I missing here??
function surgeryScheduled(srgnID){
var srgnPrsnlID = srgnID;
var sdt = document.getElementById('sdt').value;
var sdtc = sdt.toUpperCase();
var edt = document.getElementById('edt').value;
var edtc = edt.toUpperCase();
var paramString;
paramString =""
paramString += '^MINE^,'
+ srgnPrsnlID
+ ',^'
+ sdtc
+ '^,^'
+ edtc
+ '^'
var WRInfo = new XMLCclRequest();
//; Call the ccl progam and send the parameter string
WRInfo.open("GET", "CH_MP_HAVE_SURGERY_SCHED");
WRInfo.send(paramString);
//; Get the response
WRInfo.onreadystatechange = function () {
if (WRInfo.readyState == 4 && WRInfo.status == 200) {
var jsonWRResp = WRInfo.responseText;
if (jsonWRResp != undefined && jsonWRResp.length !=0) {
jsonWR = eval('(' + jsonWRResp + ')');
}
//; Make sure everything checks out, then return bool
if (jsonWR){
retval = jsonWR.SURG.EXIST_IND;
alert("INNERretval:"+retval);
}//;jsonWR
}//;WRInfo.readyState == 4 && WRInfo.status == 200
}//;WRInfo.onreadystatechange
alert("ENDRetval:"+retval);
return retval;
}

Related

SyntaxError: missing ) after argument list (line 28, file "Code.gs")

i am working on google apps script and i have come across an error which i cannot resolve.
the error occurs at the end on this line return ContentService.createTextOutput("thankyou...
I can't figure out the error. please assist me.
below is the full code
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1CIdq1anGwzUrfrNNd08NtgTR-QeHUDHgb4HOlnobmkk/edit#gid=0");
var sheet = ss.getSheetByName("Examiners");
function doGet(e){
var action = e.parameter.action;
if(action == "in")
return verified(e);
}
function doPost(e){
var action = e.parameter.action;
if(action == "in")
return verified(e);
}
function verified(e){
var id = e.parameter.id;
var values = sheet.getRange(2,1,sheet.getLastRow(),1).getValues();
for(var i = 0 ; i<values.length ; i++){
if(values[i][0] == id){
i=i+2;
var verified = Utilities.formatDate(new Date(), "EAT", "HH:mm:ss");
sheet.getRange(i,3).setValue(verified);
var fullname = sheet.getRange(i,2).getValue();
return ContentService.createTextOutput("Thank You" (fullname)"is verified at" (verified)).setMimeType(ContentService.MimeType.TEXT);
}
}
}
return ContentService.createTextOutput("Id Not Found").setMimeType(ContentService.MimeType.TEXT);
}
There were a few errors in your styling, one was how you concated strings. You used: "Thank You" (fullname)"is verified at" (verified), however this is a syntax error, as you need a + to conact several variables/strings to a string or use a template string, you got two options:
Using +: "Thank You " + fullname + " is verified at " + verified
Using template strings (Note: those are not done in quotation marks but in backticks): `Thank You ${fullname} is verified at ${verified}`
This is what I think how you mean, but I'm unsure about the last return as it was placed outside any function, I just but it one line up in the last function:
var sheet = ss.getSheetByName("Examiners");
function doGet(e) {
var action = e.parameter.action;
if (action == "in")
return verified(e);
}
function doPost(e) {
var action = e.parameter.action;
if (action == "in")
return verified(e);
}
function verified(e) {
var id = e.parameter.id;
var values = sheet.getRange(2, 1, sheet.getLastRow(), 1).getValues();
for (var i = 0; i < values.length; i++) {
if (values[i][0] == id) {
i = i + 2;
var verified = Utilities.formatDate(new Date(), "EAT", "HH:mm:ss");
sheet.getRange(i, 3).setValue(verified);
var fullname = sheet.getRange(i, 2).getValue();
return ContentService.createTextOutput("Thank You" + fullname + "is verified at" + verified).setMimeType(ContentService.MimeType.TEXT);
}
}
return ContentService.createTextOutput("Id Not Found").setMimeType(ContentService.MimeType.TEXT);
}
Furthermore I suggest you format your code better. Do you use an Editor? Many Editors can auto-format you your code, which makes it much more readable
Replace
return ContentService.createTextOutput("Thank You" (fullname)"is verified at" (verified)).setMimeType(ContentService.MimeType.TEXT);
by
return ContentService.createTextOutput("Thank You" + fullname + "is verified at" + verified ).setMimeType(ContentService.MimeType.TEXT);
Resources
Handling text — strings in JavaScript

React loop through object and render div with onClick function which takes argument

So I created a loop which goes through an object created by googles gecoding api. Finds certain values and than puts them into a "results list", the single elements have onClick functions. Now when I do the onClick functions with bind, they do work, when I do them with () => they don't. Maybe someone can explain to me why that doesn't work?
loop:
renderResults: function(){
var status = this.state.data.status;
var results = this.state.data.results;
var ok = (status === 'OK' ? true : false);
if (!status) {
return <div> </div>
}
if (!ok) {
return <div className="searchresults">Error, we couldn't find a match</div>
}
if (status && ok){
var size = Object.keys(results).length
console.log(this.state.data);
var validation_messages = this.state.data.results;
///* Get properties *///
var resul =[];
for (var key in validation_messages) {
console.log("####### " + key + " #######");
// skip loop i the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;
var label1 = '';
var label2 = '';
var obj = validation_messages[key];
console.log(obj);
for (var prop2 in obj.address_components) {
if(!obj.address_components.hasOwnProperty(prop2)) continue;
var obj3 = obj.address_components[prop2];
if (obj3.types.indexOf('locality') !== -1) {
label1 = obj3.long_name;
}
if (obj3.types.indexOf('country') !== -1) {
label2 = obj3.long_name;
}
}
var lat = obj.geometry.location.lat;
var lng = obj.geometry.location.lng;
var placeid = obj.place_id;
var label3 = lat.toFixed(3) + "°N / " + lng.toFixed(3) + "°E";
console.log('label1: '+label1);
console.log('label2: '+label2);
console.log('label3: '+label3);
console.log('lat: ' + lat);
console.log('lng: ' + lng);
console.log('id: ' + placeid);
console.log(validation_messages[key].formatted_address);
resul.push(<div className="results" onClick={this.pushlabels.bind(this, label1, label2, label3)} >{label3}</div>);
}
console.log(resul);
return resul;
}
So this works:
resul.push(<div className="results" onClick={this.pushlabels.bind(this, label1, label2, label3)} >{label3}</div>);
This doesn't work:
resul.push(<div className="results" onClick={() => this.pushlabels(label1,label2,label3)} >{label3}</div>);
What do I mean with not working? If I take the version which doesn't work than I get only pushed the label1, label2, label3 from the last object in the loop.
So now I wonder why?
It has to do with variable scoop and closures, for a similar problem have a look at javascript scope problem when lambda function refers to a variable in enclosing loop
Here's a short and simple program that illustrates what happens:
function foo(first, second){
console.log(first + " : " + second)
}
var x = "x";
let bar = () => {foo("bar", x)}
let baz = foo.bind(this,"baz", x)
bar()
baz()
x = "y"
bar()
baz()
//Output:
//bar : x
//baz : x
//bar : y
//baz : x
So basically bind makes the function remember (it actually returns a new function with the parameters set) the current state of the variables. Where as a lamda looks at the variables when it's executed. That's why you only see the last three labels when you don't use bind.

return a substring using indexOf as a parameter within a function

I'm supposed to create a functions to test a URL for validity then functions to look for and return parts of the URL string based on location of certain characters (position would be unknown). FYI, I'm very new to programming but have been searching and trying many answers. My latest attempt uses below format (found in an answer) but still can not get anything but an empty string to display when I call the function.
When I run this in Chrome, and enter "http://www.niagaracollege.ca" or "http://lego.ca" even though I am entering a valid URL, I get a return of false.
function validURL(userInput)
{
input = new String(userInput);
if (input.indexOf("://") != -1 && input.lastIndexOf(".") != -1)
return true;
else
return false;
}
function findProtocol(userInput)
{
input = new String(userInput);
var result = input.substring(0, input.indexOf("://"));
return result;
}
function findServer(userInput)
{
input = new String(userInput);
var result = input.substring(input.indexOf("://") + 1 ,input.lastIndexOf("."));
return result;
}
function findDomain(userInput)
{
input = new String(userInput);
var result = input.substring(input.lastIndexOf(".") + 1);
return result;
}
function btnReadURL_onclick()
{
var userInput = document.getElementById("txtURL").value;
var outputBox = document.getElementById("txtOutput");
var URL = validURL(userInput);
if (URL = true)
{
var Part1 = findProtocol(userInput);
var Part2 = findServer(userInput);
var Part3 = findDomain(userInput);
outputBox.value = "Protocol: " + Part1 + "\nServer: " + Part2 +
"\nDomain: " + Part3;
}
else (URL == true)
outputBox.value = "Invalid URL";
}
Use a debugger to find out what you are getting in the userInput. The code is fine. It should work. See sample code below.
test = function() {
var test = "http://Test 2"
alert(test.substring(0, test.indexOf("://")))
}
You need to pass the value to the findProtocol method rather than DOM element
Replace
var userInput = document.getElementById("txtURL");
by
var userInput = document.getElementById("txtURL").value;
and replace
if (URL = true)
with
if( URL == true )

readyState will not change to 4

I am trying to create a dynamic AJAX search bar which communicates with my database. Here is my code.
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
var search = getXmlHttpRequestObject();
function ajaxSearch(){
if (search.readyState == 4 || search.readyState == 0){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", 'searchSuggest.php?search=' + str, true);
search.onreadystatechange.handleSearchSuggest;
search.send(null);
}
}
function handleSearchSuggest(){
if(search.readyState == 4){
var ss = document.getElementById('ajaxSearch');
ss.innerHTML = '';
var str = search.responseText.split("\n");
for(i=0; i<str.length-1; i++){
var suggestion = '<div onmouseover="javascript:suggestOver(this);"';
suggestion += 'onmouseout="javascript.suggestOut(this);"';
suggestion += 'onclick="javascript:setSearch(this.innerHTML);"';
suggestion += 'class="suggestLink">' + str[i] + '<div>';
ss.innerHTML += suggestion;
}
}
}
function suggestOver(divValue){
divValue.className = "suggestLink";
}
function suggestOut(divValue){
divValue.className = "suggestLink";
}
function setSearch(x){
document.getElementById('searchBox').value = x;
document.getElementById('ajaxSearch').innerHTML = '';
}
The problem is that the readyState is changing from 0 to 1, but then it will not change to any other state. I need it to change to 4 to enter the function handleSearchSuggest().
I also get this error within the console:
TypeError: search.onreadystatechange is null
You need to set the callback function correctly.
search.onreadystatechange = handleSearchSuggest;
Note that a ready state of 1 means OPENED and 4 means DONE. You can test this via properties of the XMLHttpRequest class:
XMLHttpRequest.UNSENT == 0
XMLHttpRequest.OPENED == 1
XMLHttpRequest.HEADERS_RECEIVED == 2
XMLHttpRequest.LOADING == 3
XMLHttpRequest.DONE == 4
Try:
search.onreadystatechange = handleSearchSuggest;

JS: Can not convert to object, childNodes related

Ok, feeling stupid here, but wondering what the problem is here exactly.
Although the function works as it should, I get this JS Error in Opera. Not sure about other browsers...
Uncaught exception: TypeError: Cannot
convert
'document.getElementById("shoutbox_area"
+ moduleId)' to object
oElement = document.getElementById("shoutbox_area"
+ moduleId).childNodes;
Here is the relevant code:
function appendShout(XMLDoc)
{
var shoutData = XMLDoc.getElementsByTagName("item");
var oElement = [];
if (shoutData.length > 0)
{
var moduleId = shoutData[0].getAttribute("moduleid");
if (shoutData[shoutData.length - 1].getAttribute("lastshout") != "undefined")
{
for (var i = 0; i < shoutData.length; i++)
if (shoutData[i].firstChild.nodeValue != 0)
document.getElementById("shoutbox_area" + moduleId).innerHTML += shoutData[i].firstChild.nodeValue;
oElement = document.getElementById("shoutbox_area" + moduleId).childNodes;
var i = oElement.length;
while (i--)
{
if (i % 2 == 0)
oElement[i].className = "windowbg2";
else
oElement[i].className = "windowbg";
}
oElement[oElement.length - 2].style.borderBottom = "1px black dashed";
}
}
}
Can someone please help me to understand why it is giving me an error here:
oElement = document.getElementById("shoutbox_area" + moduleId).childNodes;
Can I not assign an array to the childNodes?
EDIT:
This JS Error occurs when I try and delete a shout. The JS function for deleting a shout is this:
function removeShout(shout, moduleID)
{
var shoutContainer = shout.parentNode.parentNode;
var send_data = "id_shout=" + shout.id;
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dream;sa=shoutbox;xml;" + "delete_shout;" + "canmod=" + canMod[moduleID] + ";" + sessVar + "=" + sessId;
sendXMLDocument(url, send_data);
var shoutID = 0;
while (shoutID !== null)
{
var shoutID = document.getElementById(shout.parentNode.id);
var moduleID = shoutID.parentNode.getAttribute("moduleid");
if (shoutID.parentNode.lastChild)
{
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dream;sa=shoutbox;xml;get_shouts=" + (shoutID.parentNode.lastChild.id.replace("shout_", "") - 1) + ";membercolor=" + memberColor[moduleID] + ";maxcount=" + maxCount[moduleID] + ";shoutboxid=" + shoutboxID[moduleID] + ";textsize=" + textSize[moduleID] + ";parsebbc=" + parseBBC[moduleID] + ";moduleid=" + moduleID + ";maxcount=" + maxCount[moduleID] + ";canmod=" + canMod[moduleID] + ";" + sessVar + "=" + sessId;
getXMLDocument(url, appendShout);
}
element = shoutID.parentNode.childNodes;
var i = element.length;
while (i--)
{
if (i % 2 == 0)
element[i].className = "windowbg2";
else
element[i].className = "windowbg";
}
shoutID.parentNode.removeChild(shoutID);
}
}
Am using the following functions for the sending and getting the XMLHttpRequest as you may have noticed already in the removeShout function above:
// Load an XML document using XMLHttpRequest.
function getXMLDocument(sUrl, funcCallback)
{
if (!window.XMLHttpRequest)
return null;
var oMyDoc = new XMLHttpRequest();
var bAsync = typeof(funcCallback) != 'undefined';
var oCaller = this;
if (bAsync)
{
oMyDoc.onreadystatechange = function () {
if (oMyDoc.readyState != 4)
return;
if (oMyDoc.responseXML != null && oMyDoc.status == 200)
{
if (funcCallback.call)
{
funcCallback.call(oCaller, oMyDoc.responseXML);
}
// A primitive substitute for the call method to support IE 5.0.
else
{
oCaller.tmpMethod = funcCallback;
oCaller.tmpMethod(oMyDoc.responseXML);
delete oCaller.tmpMethod;
}
}
};
}
oMyDoc.open('GET', sUrl, bAsync);
oMyDoc.send(null);
return oMyDoc;
}
// Send a post form to the server using XMLHttpRequest.
function sendXMLDocument(sUrl, sContent, funcCallback)
{
if (!window.XMLHttpRequest)
return false;
var oSendDoc = new window.XMLHttpRequest();
var oCaller = this;
if (typeof(funcCallback) != 'undefined')
{
oSendDoc.onreadystatechange = function () {
if (oSendDoc.readyState != 4)
return;
if (oSendDoc.responseXML != null && oSendDoc.status == 200)
funcCallback.call(oCaller, oSendDoc.responseXML);
else
funcCallback.call(oCaller, false);
};
}
oSendDoc.open('POST', sUrl, true);
if ('setRequestHeader' in oSendDoc)
oSendDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
oSendDoc.send(sContent);
return true;
}
Hopefully this is good enough, you can do a view source on it to see the actual HTML, but there are attributes that get added to the Shoutbox tags at runtime so as to be XHTML compliant, etc..
Please let me know if there is anything else you need?
Thanks :)
The code is breaking because shoutID is null in the second of these two lines, the second time through the loop:
var shoutID = document.getElementById(shout.parentNode.id);
var moduleID = shoutID.parentNode.getAttribute("moduleid");
The first of those lines is strange. Why not just use var shoutID = shout.parentNode;?
Also, the moduleId attribute seems to be nowhere around.
What are you trying to achieve with the while loop?

Categories