JavaScript / AJAX / Servlet compare Strings - javascript

I am trying to compare a string that is returned from servlet
Servlet page returns this:
out.println("pass");
JavaScript:
function Return() {
if (ajax.responseText === "pass") {
document.getElementById("pass").innerHTML = "This is valid number!";}
Now I have output the ("ajax.responseText") and it returns "pass" but I can't still validate it in the IF statement.
I tried using (.equal("pass") i tried with == and I even tried "var value = ajax.responseText; and then tried value === "pass")
Yes I also tried .toString()..
It just never validates it correctly it always goes to ELSE statement...

println usually appends a line break at the end of the string (the "ln" in println stands for "line") and thus the string value returned by the server is actually "print\n" (or something similar), which is not equal to "pass".
If available, use
out.print("pass");
which doesn't append a line break.
Or trim the response before comparison.

Instead of your original function Return (which doesn't explicitly return)
function Return() { // Why not checkPassword?
if (ajax.responseText === "pass") { // exactly equal
document.getElementById("pass").innerHTML = "This is valid number!";
}
}
Try something like this (e.g. presumably it should be true or false, so do so explicitly)...
function checkPassword() { // probably should pass arguments what the function does.
if (ajax.responseText.trim() == "pass") { // trim the response string
// ('pass\n' != 'pass')
console.log('Got a match!'); // Try logging it.
document.getElementById("pass").innerHTML = "This is valid number!";
return true; // return a value?
} else {
// Again, I would try adding some debug logging.
console.log('Did not match! ' + ajax.responseText);
}
return false; // default to false.
}

Related

Awaiting code until filter is finished - Nextjs/Javascript

I am looking on how to make my code after my filter function await the results of my filter function to complete before running. However I am not sure how to do this.
My filter function takes in another function (useLocalCompare) which causes the execution of my filter function to be a little longer than normal, which then leads to my next piece of code (that depends on the results of my filter function) executing before my filter function is complete.....which leads to undefined.
Is there anything similar to a callback I can use to force my subsequent piece of code to wait till the filter is finished?
Relevant code is written below.
if (flatarrayofvalues !== null && genre !== null) {
const filtteredarray = await flatarrayofvalues.filter(
(placeholder) => {
if (useLocalCompare(genre, placeholder.name) == true) {
console.log("HURAY!!!!", placeholder.id, placeholder.name);
placeholder.name == placeholder.name;
}
}
);
console.log("MY FILTERED ARRAY IS", filtteredarray);
console.log("The ID FOR MY MY FILERED ARRAY IS two ID", filtteredarray[0]?.id);
return filtteredarray[0].id;
}
}
}
For those curious, useLocalCompare basically checks to see if the genre parameter pulled down from the URL is the same as a name parameter from the array I am filtering. Reason I have this is due to people having different case sensitivity when putting in URLS. EX: it will pull down "HORrOR" and match it to the object name in the array I am filtering called "horror". I then extract the ID from that object.
you have to return the conditional from filter as it is "explicit return"
const filtteredarray = await flatarrayofvalues.filter(
(placeholder) => {
if (useLocalCompare(genre, placeholder.name) == true) {
console.log("HURAY!!!!", placeholder.id, placeholder.name);
return placeholder.name == placeholder.name; // here
// why not just return true ?? instead of above line
}return false
}
);
Also I'm not sure this makes sense
placeholder.name == placeholder.name; you mean just return true; ?

EnableRule in ribbon cannot get boolean value from async function

I want to return true or false from the function showHideAddNewButton. I have an EnableRule in a ribbon button, which calls a custom rule that calls this function showHideAddNewButton. On passing either true, which will show the button, or false, which will hide the button.
I have to access statuscode (Status Reason) and statecode (Status) fields on the entity. I have created a query using the Xrm.WebApi.retrieveMultipleRecords, but cannot get it to return a flag. I want the retrieveMultipleRecords method to only execute on and never be called again but 'return true' below gets executed setting my button to true always.
function showHideAddNewCsrsRecalculation(primaryControl){
var fileNumber = primaryControl.getAttribute("ssg_filenumber").getValue();
Xrm.WebApi.retrieveMultipleRecords("rrg_csrsfile", "?$select=statuscode,statecode,rr_filenumber&$filter=rr_filenumber eq '" + fileNumber + "'").then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
var statusCode = result.entities[i].statecode;
var statusReasonCode = result.entities[i].statuscode;
//if draft make button invisible
if (statusReasonCode == 8676725)
return false;
//if submitted make button invisible
if (statusReasonCode == 8676726)
return false;
//if inactive make button invisible
if (statusCode == 1)
return false;
}
},
function (error) {
console.log(error.message);
// handle error conditions
}
);
//if draft make button invisible
//if (primaryControl.getAttribute("statuscode").getValue() == 867670025)
// return false;
//if submitted make button invisible
//if (primaryControl.getAttribute("statuscode").getValue() == 867670026)
// return false;
//if inactive make button invisible
//if (primaryControl.getAttribute("statecode") != 'undefined' && primaryControl.getAttribute("statecode").getValue() == 1)
// return false;
//other options make button visible
return true; --> This keeps getting called as a result my button is always visible
}
Function Xrm.WebApi.retrieveMultipleRecords returns a promise, not an actual boolean value. The function is executed asynchronously, so immediately after the call to this function the next line is executed and that line always returns true.
In fact it is not possible to make an asynchronous call synchronous. Instead we can follow another approach by following these steps:
Do the query in the form's onload function and store the result in a variable.
Refresh the ribbon.
Create a ribbon button handler returning the variable's value.
let isRecalculationButtonVisible = false;
function onLoad(context) {
const formContext = context.getFormContext();
const filter = "$filter=rr_filenumber eq '"
+ formContext.getAttribute("ssg_filenumber").getValue()
+ "' and (statecode eq 1 or statuscode eq 8676725 or statuscode eq 8676726)";
Xrm.WebApi.retrieveMultipleRecords("rrg_csrsfile", "?$select=rrg_csrsfileid&$top=1&" + filter)
.then(function (result) {
isRecalculationButtonVisible = result.entities.length === 0;
})
.catch(function (error) {
console.log(error.message);
})
.finally(() => {
formContext.ui.refreshRibbon(false);
});
}
function showHideAddNewCsrsRecalculation() {
return isRecalculationButtonVisible;
}
As you probably already noticed I added a few improvements.
All your button needs to know is if there are any records meeting specific conditions, so there is no need to actually retrieve them. Therefore these conditions can simply be placed in the query's filter. I also added a $top=1, because the number of records meeting the conditions is not relevant here. As a consequence the only check that needs to be done is whether a record is returned or not.
As explained, retrieveMultipleRecords returns a promise. The recommended error handling for promises is adding a catch function at the end of the chain.

Why is the condition in this callback always returns false?

I have a home SPA based on Vue. One of the components is driven by a v-if="isDisplayed".
This isDisplayed is set by listening to a MQTT topic (see footnote) and new messages received are handled by the following function (I sepcifically used 'hello' instead of false to make sure the switch goes there). The topic of interest is display_school_edt.
mqttMessage(topic, message) {
console.log(`App.vue received topic ${topic} with payload '${message}'`)
if (topic === "dash/reload") {
window.location.href = window.location.href
document.location.reload(true);
}
if (topic === "dash/darkmode") {
this.nightmode = JSON.parse(message) ? "night" : "day";
}
// this is the part I have problems with, I left everything for completness
if (topic === "display_school_edt") {
console.log(`edt display received: '${message}'`);
if (message === 'on') {
this.isEdtDisplayed = true
} else {
this.isEdtDisplayed = 'hello'
}
// I initially went for the ternary below - same results
// message === "on" ? this.isEdtDisplayed = true : this.isEdtDisplayed = 'hello';
console.log(`new edt display: ${this.isEdtDisplayed}`);
}
}
When I publish to the monitored topic display_school_edt (twice: one the message is on and the other time off), here is what I get on the console:
In other words, no matter if on or off is received, the condition is always false.
There is something obviously wrong with my code but the more I look, the better it looks.
Footnote: the fact that it is that specific protocol does not matter (it is a kind of bus often used with IoTs), you can assume that somehow mqttMessage() is executed with the parameters topic and message that are both strings.
This is indeed unexpected if message is of type string. However, it probably is not, and the only times you output message, you actually coerce it to string. So if you see from a previous output that it coerces to "no", then in the if condition you should do the same, and force that conversion to string:
if (message+'' === 'no')
NB: This will call message.toString(), just like it does when you reference it within a template literal as ${message}.

Javascript, how to check if object exists

I am making a script in Javascript script that gets a SQL response, then processes it. Basically, I want to check if the username value exists in result[1]. When it checks, it errors out and says that it does not exist. If it does not exist, I want it to return false, not stop the program.
Here is the code:
if (result[1].username != undefined) {
return true;
} else {
return false;
}
I have tried using typeof(result1) == undefined, but it gives me the same error.
First, you have to make sure the result exists, otherwise you'd be indexing into undefined which would crash your application.
Second, you can make that check less verbose with:
return (result[1] && result[1].username)
which will return a falsey value if it doesn't exist, and whatever the username is, if it does.
In case you need an explicit true to be what the function returns, you can coerce it:
return (result[1] && (result[1].username && true))
I would make sure to refactor for readability, but that's the gist.
You could use the in operator. For example:
let trueObj = { username: 'Foo' };
let falseObj = { };
if ('username' in trueObj) {
console.log('username found in trueObj');
} else {
console.log('username not found in trueObj')
}
if ('username' in falseObj) {
console.log('username found in falseObj');
} else {
console.log('username not found in falseObj')
}
First of all please check whether the result itself exists or not and make the corresponding & operator and i think this will definitely help
if (result && result[1] && result[1].username) {
return true;
} else {
return false;
}
But if you don't want to make your code complex then you can try lodash library.
https://lodash.com/

looping the local storage

I want to loop the local storage for the password and username to check if correct and alert a message if or if not.
The code is working well, but I don't know where to write the "invalid username" message because the loop goes through every record, so the messages pops ups for every record check until it finds it.
What I want is to pop up the message when the search is done.
Here is my code:
$("#login").click(function(){
var username =$("#user").val();
var password =$("#pass").val();
var userCount = localStorage.getItem('userCount');
for (i=1;i<=userCount;i++) {
var user = JSON.parse(localStorage.getItem("user" + i));
if((user.username == username)||(user.password == password)){
alert("welcome "+username);
} else {
alert("Invalid Username");//this message keeps poping up on every record until username found
}
}
});
Put the loop inside a function.
Return true (or the user object) from that function if anything inside the loop matched.
Return false after the loop (which you'll only reach if nothing matches).
Handle your alert outside the function based on the return value of calling it.
Set a boolean variable to true when you find a match, and stop the loop using break. Otherwise, if the boolean is still false after the loop completes, no match was found.
$("#login").click(function(){
var username =$("#user").val();
var password =$("#pass").val();
var userCount = localStorage.getItem('userCount');
var foundOne = false;
for (i=1;i<=userCount;i++) {
var user = JSON.parse(localStorage.getItem("user" + i));
if((user.username == username)&&(user.password == password)){
foundOne = true;
break;
}
}
if(foundOne) {
alert("welcome "+username);
// other "welcome" code
} else {
alert("Invalid Username");
}
});
NB, you may want to use the && operator instead of || here:
(user.username == username)&&(user.password == password)
otherwise you may get a match for one user who has the same password as another.

Categories