javascript: How to show a message using an alert after Ajax request - javascript

I am trying to display an alert after an Ajax request has been submited successfully.
$.post(
"ajax_request.php", {
email: email
},
function(data) {
$('#message').html(data);
var y = $('#message').text();
if (y == 'exists') {
alert('text');
}
);
The script above works, but I cannot display the alert, although the var y contains the word exists.

Change to this:
if(y.indexOf('exists') != -1){
alert('text');
}

If you wish to check if one string contains another, use the following code:
if (y.indexOf('exists') > -1) {
alert('test');
}
Reading Material
indexOf()

== is used for comparing if two variables are equal or not. It doesn't check data type.
=== is used for comparing two variables if they are equal as well as their data type is same.
In your case, you don't have to use any of them because you need to check whether a string contains a substring or not.
To check whether a string contains a particular substring or not, you need to use indexOf().
Now, Assuming that you are getting some data as the response and somehow storing it in variable y.
Now, to check whether y contains word 'exists' or not, you should check it the following way.
if(y.indexOf('exists) != -1) {
//do something
}
Let's define y and check
var y = "Does this sentence contain word exist?";
y.indexOf('exist');
Output : 32
If y doesn't contain exist, then the output would have been 1.

Related

How to access the first two digits of a number

I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!

How do you compare two variables in Javascript?

I am trying to compare two different variables with each other and execute certain code if they match.
The variables are: userInput and commandOne
Firstly, a button is pressed to call myTest().
function myTest() {
userInput = document.getElementById("runBox").value;
testInput();
}
The function gathers text from an input box on my page and stores it in a variable named userInput. It then calls my next function...
function testInput() {
if (userInput = commandOne) {
document.getElementById("demo").innerHTML += "<br>executed!";
}else {
alert("this is an alert message");
}
}
This part is designed to test if userInput matches the variable named commandOne. (commandOne's value is currently set to "ip").
If it does match, it will add text (executed!) to a paragraph with the "demo" ID. If it does not match, it will alert the user in an alert box.
My problem is that the variables do not seem to be comparing. No matter what the user puts into userInput the text (executed!) is always outputted to my paragraph. It appears that the browser thinks they are matching when they are not.
You missed your operator in the if statement.
if (userInput == commandOne)
== compares value
if (userInput === commandOne)
=== compares values and data types.
You had used the wrong operator. You must use == sign instead of a single = sign.
function testInput() {
if (userInput == commandOne) {
document.getElementById("demo").innerHTML += "<br />executed!";
} else {
alert("This is an alert message");
}
}
A single = sign (=) means that the value on the left side of the sign gets the same value as on the right side of the sign.
Double= sign (==) means that two values on the each side of the sign are equal.
Triple = sign (===) means that both the values are equal and of the same type.
Click here for more information.
As mentioned - you have the wrong operator - however i just wanted to show an alternative to the logic: - the ternary operator - makes it much nicer and cleaner to read and reduces the if / else markup.
Incidentally - given the code provided - you don't even need to call teh second function - the entire thing can be done in one function. Also - if the alert is purely to demonstrate the "else" outcome - you should investigae the use of the console.log() - its bettter for debugging.
To explain the ternary operator - the condition to be met is written first (note that there is no "if" preceding it. Following it - use the "?" charcter to give an action if hte comparison is true and use a ":" character for if the outcome is false.
Note that I always write the ternary operators on the three lines as i have done here - I find it easier to read - it can all be written on one line - personal preference.
And last thing - no ";" at the end of the "true" portion of the statemtn - it is all one expression that I happen to have written over three lines.
function testInput() {
userInput == commandOne
? document.getElementById("demo").innerHTML += "<br>executed!"
: alert("this is an alert message");
}

Get a value from URL and create a Javascript function

I am new on this website, and I am also new at Javascript.
What I would do is get a value from a link, eg:
http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741
I need to take this value: O=107905, if it is only one code I need to run a file (file A),
if it look like this: O=107905~107906, then I need to run a different file (file B).
What I thought is create a function with javascript where if it is (~) is missing, then will be used the file A, if there is one or more than one of (~) then the file B will start to work.
Many thanks in advance!
Well. We really do encourage you to provide your own code first before providing solutions, but this is a fairly simple problem in javascript. Here's my take on it.
The first problem you have to solve is actually getting the query string parameters in a meaningful format. Here I create an object that uses the query string keys as the object keys (IE 9+ only because of the forEach)
var tmpObject = {}
location.search.substr(1).split('&').forEach(function(item){
var o = item.split('=');
tmpObject[o.shift()] = o.shift();
});
Then it's just a matter of making sure the query string contained the target object (in this case "O") and determine if there is more than one.
if(tmpObject.hasOwnProperty('O') && tmpObject.O.split('~').length > 1) {
console.log('return multiple files');
} else {
console.log('return one file');
}
Try this
var url = "http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741";
var search = url.substring(url.indexOf("?")+1);
var map={};
search.forEach(function(val){var items=val.split("="); map[items[0]]=items[1];});
if (map["O"].indexOf("~") != -1)
{
//O value has ~ in it
}
else
{
//O has no ~ in it
}
Possible solution to get the paramter would be there : How to get the value from the GET parameters?
Once you have the parameter value, you can for sure look if you find '~' with String.prototype.indexOf.
String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.

How can I check if the user input with the database information?

I have a JavaScript programme that randomly selects an image of an object from the database and display that image to the user. The image is saved with the object name (i.e. apple.gif)
I am using the following code in order to check whether the user input response is the correct answer to the test or not:
However the code does not do anything. Could anyone let me know what the problem is please?
Look at your JavaScript console:
Uncaught ReferenceError: random_image_array is not defined
You made a typo. When you defined the variable you said images (with an s).
function checkUserInput() {
var userInput = document.getElementById("textInput").value;
var stringToCheckAgainst = random_image_array[num].split('.');
//this splits the item at the array index into an array, like so. If the item is "apple.gif", the array reads ["apple", "gif"]
if (userInput == stringToCheckAgainst[0]) {
//user has inputted the correct string
document.write("Correct!");
} else {
//user has inputted an incorrect string
document.write("Incorrect response!");
}
}
The above is a function. In order to use the function, you must call it.

If Statement Have A String And Other String (Make To List)

Sorry i cant find the tutorial in google because i dont know the keyword...
var currentURL=location.href;
var str = currentURL;
if(str == "http://web.com/blabla" || str == "http://web.com/bleble"){
window.location = "http://web.com/ban";
} else {
}
How to make str == "http://web.com/blabla" || str == "http://web.com/bleble" to list ? so if i want to input some url again, i just input the url to the list. Can give me the code or link tutorial ???
Basically you'll need to place all of your URL's into an array and then iterate over the array checking each item.
var urls = ['http://web.com/','http://web.net/','http://web.org'];
var current_url = '...';
for (var i = 0; i < urls.length; i++){
if (current_url == urls[i]){
window.location = "http://web.com/ban";
break; // exit the loop since we have already found a match
}
}
The break command will terminate the loop and stop searching the array for matching URLs. Since the action you want to take needs to happen if any of the URLs match, it's enough for one to match in order to stop searching.
Lists are called arrays in javascript, and are declared using square brackets, like this: var badUrls = ["http://web.com/blabla", "http://web.com/bleble"].
To check whether the current URL appears in the array, you can use the .indexOf function of the array, which will return the first position in the array where the string you provide can be found (starting with 0 for the first element), or -1 if it doesn't exist. For example, if you have an array var arr = ["foobar", "foo", "bar", "baz"], and you do arr.indexOf("foo"), you get 1 because it's the 2nd element in the array. If instead you do arr.indexOf("fooba"), you will get -1 because none of the elements in the array are fooba exactly. In your code, you want to redirect the user if badUrls.indexOf(str) > -1. You can get more information on indexOf in the MDN Documentation.
That makes your code look like:
var currentURL=location.href;
var str = currentURL;
var badUrls = ["http://web.com/blabla", "http://web.com/bleble"]
if(badUrls.indexOf(str) > -1){
window.location = "http://web.com/ban";
} else {
}
window.location is a browser object, it you want the page to go to http://web.com/ban, you should use
window.location.href = "http://example.com/ban";
However, it looks like you are trying to prevent people from visiting pages using JavaScript. This is extremely insecure, because anyone that lists your code will see which URLs you're trying to protect and immediately request them. If they request those URLs with JavaScript disabled, or using curl, the pages will be delivered.
You should protect the pages with server side configuration. With Apache, you can use the Allow/Deny configuration or RewriteRules.

Categories

Resources