Block specific keyword search from form - javascript

my search form on my page is
<form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech">
<input type="text" name="search" id="jsid-search-input" value="<?php echo$_GET['search']; ?>" class="ui-autocomplete-input search search_input" placeholder="Search…" tabindex="1"/>
<div class="ui-widget"></div>
</form>
i dont want users to be able to search certain words....
if they search "f***" i want it to redirect to the home page or a simple javascript notification that says not allowed.... thanks!

Either trap for bad words in your php script, or put your php request behind some javascript and trap there. example....
html...
<html>
<head>
<link rel="stylesheet" href="style.css"></link>
<script src="functions.js"></script>
</head>
<body>
<form id="headbar-search">
<input type="text" id="search-box"/>
<input type="submit" onclick="search();"></input>
</form>
</body>
</html>
js...
var badWords = ["gosh","darn"];
function search() {
var searchStr = document.getElementById("search-box").value;
var badWordHit = false;
for (key in badWords) {
if (badWords[key] == searchStr) {
badWordHit = true;
}
}
if (badWordHit) {
alert("Oh no you didn't!");
} else {
// ajax request here
}
}

Related

How do I manually test JavaScript?

I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>

JS window.location not working

My window.location does not redirect the page to the required location. The same code with window.open works. The else statement also executes when the user name and password are incorrect. When the correct username and password is entered, it just refreshes the same page.
<div class="login" style="position:relative;top:200px;">
<form name="login" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<script language="javascript">
function check(form) {
if(form.login.value == "admin" && form.pwd.value == "sysadmin") {
window.location('alumni.html');
}
else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
You can also try with
window.location = 'http://www.yoururl.com/alumni.html';
or directly
window.location = 'alumni.html';
There is a good question about redirect in javascript here: How do I redirect with Javascript?
[EDIT #1]
Although I think that is not the main problem. I believe you can not validate the way you are doing it. In the form there is an attribute called action as explained in http://www.w3schools.com/tags/att_form_action.asp
Then in the page you load, you validate the parameters and decide if its right or not, where you redirect to one page if its right, or to another if it's wrong.
Or you can also load the page and if validation is right, stay in the page and if it's wrong redirect to the login page.
That's one way to do it, probably there is another one better.
[EDIT #2]
What I would personally do is to process the form in a PHP page, it's much easier and simpler. Could be like:
in the HTML:
<div class="login" style="position:relative;top:200px;">
<form name="login" action="myPhpPage.php" method="post">
<p align="middle">Please login to continue </p>
<p align="middle"><input type="text" name="login" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle">
<input type="submit" onclick ="" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
In the PHP page:
$name = $_POST['login']; // it's $_post because you are sending the form with method = post
$pass = $_POST['pwd'];
if($name == "admin" && $pass == "sysadmin"){
//go to one page or stay here
} else{
// redirect to another page
}
window.location is a read only property:
The Window.location read-only property returns a Location object with information about the current location of the document.
MDN on window.location
try this: window.location.replace("http://stackoverflow.com");
Here's a working code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Login Redirection Test</title>
<script>
function validateForm() {
var un = document.forms["login"]["user"].value;
var pw = document.forms["login"]["pwd"].value;
if (un == "admin" && pw=="sysadmin") {
window.location.assign="https://stackoverflow.com";
return false;
}else {
alert("Ten thousand thundering typhoons! What is the blasted password?");
}
}
</script>
</head>
<body>
<div class="login" style="position:relative;top:200px;">
<form name="login" onsubmit="return validateForm()" method="post">
<p align="middle">Please login to continue </p><p align="middle"><input type="text" name="user" placeholder="Username"></p>
<p align="middle"><input type="password" name="pwd" placeholder="Password"></p>
<p class="submit" align="middle"><input type="submit" onclick ="return check(this.form)" value="Login" name="commit"></p>
</form>
<!--<script type='text/javascript' src='alumna.json'></script> -->
</div>
</body>
</html>
Window.location is not a function, it is a property that is just read. However,
window.location.assign
might work better.

Validating and linking to another page

I have created a login page.In whicn iam unable to link it with the next page after clicking submit button.I want to validate and redirect to the next page.ie home.php.Kindly help me find out what am i missing.
signin.php
<!DOCTYPE html>
<html>
<head>
<script>
function val()
{
var a=document.signin.user.value;
var b=document.signin.password.value;
if ( a == "admin" && b == "rec"){
alert ("Login success");
window.location = "home.php";
return false;
}
else{
alert("login failed")
}
}
</script>
<meta charset="UTF-8">
<title>LIBRARY </title>
</head>
<body>
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>REC<span>LIBRARY</span></div>
</div>
<br>
<br>
<br>
<div class="login">
<form name="signin" method="post" onsubmit="val();">
<input type="text" placeholder="username" name="user"><br>
<input type="password" placeholder="password" name="password"><br>
<input type="submit" id="mybutton" value="login"></form>
</div>
</body>
</html>
The problem is the onsubmit event is not having false returned to it, so it posts the form normally, after your JavaScript has finished. Even in the case of successful login and the redirect is executed, the form will still submit and it will override the redirect.
Firstly, Move your return false; to the end of the function, so that it always executes.
Secondly, change your onsubmit="val();" to onsubmit="return val();". This means the onsubmit event will always be returned false and will not try to post the form.
Side note: this is by no means a secure system. Any visitor can simply observe the HTML source to find the password, or just navigate directly to home.php. For a secure system, you will need to do the authentication on the server side (in the PHP).
You could use preventDefault() Event method without using onsubmit=val() like below.
document.getElementById("signin").addEventListener("submit", function(e){
e.preventDefault()
// actual code to validate
});
or
can try some dirty work on server side directly to hide the validation part
<?php
ob_start();
session_start();
loginForm();
$userinfo = array(
'admin'=>'0b2c082c00e002a2f571cbe340644239'
);
if(isset($_POST['username'])){
if($userinfo[$_POST['username']] == md5($_POST['password'])){
$_SESSION['username'] = $_POST['username'];
header('Location: home.php');
exit();
}else{
?>
<script type="text/javascript">
alert("Oops.... User name or Pasword is worng, Please try again");
</script>
<?php
}
}
function loginForm()
{
?>
<form name="login" action="" method="post">
Username: <input type="text" name="username"> <br><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="login">
</form>
<?php
}
?>

preventDefault and JSONP

We have a form that should post data to an external domain. We are aware of the cross-domain limitations, therefore we want to use JSONP.
All parts are working fine, except for the part that should prevent a default form submission that reloads the page. Below is the form.
The html page:
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://gateway.wildfx.com/test.js"></script>
</head>
<body>
<form method="POST" id="wild">
<fieldset>
<label for="email">Your email:</label>
<input type="text" name="email" id="wild">
<p class="wild_err">invalid</p>
<p>
<input type="hidden" id="wild_v" name="v" value="test2">
<input type="hidden" id="wild_l" name="l" value="">
<input type="hidden" id="wild_i" name="i" value="identifier">
<input type="hidden" id="wild_s" name="s" value="10612">
<input type="submit" id="wild_button" value="Check">
</p>
</fieldset>
</form>
</body>
</html>
Below is the Javascript. However, if the wild form is submitted, the page reloads instead of transfering the data with JSONp. In addition even the submission2 log isn't logged.
If tried to replace the .submit() with .click for the from button with correct ID but it isn't working either. What is wrong with the script?
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
console.log('submission1');
$("#wild").submit(function(e) {
console.log('submission2');
e.preventDefault();
if (isValidEmailAddress(e["e"])) {
var e = {};
e["e"] = $("#wild_email").val();
e["v"] = $("#wild_v").val();
e["i"] = $("#wild_i").val();
e["s"] = $("#wild_s").val();
e["l"] = $("#wild_l").val();
(function() {
var wildAPI = "https://gateway.wildfx.com/testjsonp.php?jsoncallback=?";
$.getJSON( wildAPI, {
tagmode: e,
format: "json"
})
.done(function( data ) {
$(".wild_message_container").text('Success. you are in');
setTimeout(function() {
$("#wildnotifier-container").hide();
$("#wildnotifier-overlay").hide();
}, 5000);
});
})();
} else {
$(".wild_error").show();
$("#wild_email").addClass("wild_input_error");
}
});
You load jQuery
You load your script
Your script tries to add an event handler to the form
You add the form to your page
Step 3 fails because the form doesn't exist. Move the script so it is after the form. (Or put it in a function and call it with the DOM is ready).

Can we pass form element values to a function in the same web page?

<html>
<body>
<form action="">
......any form elements......
</form>
</body>
<script>
function fn() {
}
</script>
</html>
Instead of an URL in the action attribute, is there a way (or any other alternate way) to pass values of form to a function (within script tags) within this same web page?
Here is how I have done it for years. It works on all browsers - for really old browsers you can even change document.getElementById("form1") to document.form1 if you add name="form1" to the form tag.
Note: Before jQuery, it was in many places recommended practice to use eventListeners such as
document.getElementById("form1").addEventListener("submit",
function(e) {
e.preventDefault();
... some code
});
but I personally prefer either jQuery or the simpler onsubmit...
<html>
<head>
<script>
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
var val1 = this.field1.value;
if (val1=="") {
alert('Field1 cannot be empty');
this.field1.focus();
return false;
}
// return true to submit, return false to stay on the page.
return true;
}
}
</script>
</head>
<body>
<form id="form1" action="">
<input type="text" name="field1" value="" />
.
.
.
</form>
</body>
</html>
If it MUST be inline, then I strongly recommend
<head>
<script>
function validate(theForm) {
var val1 = theForm.field1.value;
.
.
return false;// cancel
.
.
return true; // allow submit
}
</script>
</head>
<form onsubmit="return validate(this)">
UPDATE
to just change some span or div on the page do this:
<html>
<head>
<script>
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
var val1 = this.field1.value;
document.getElementById("div1").innerHTML="This is the value "+val1;
return false; // do not submit/refresh the page
}
}
</script>
</head>
<body>
<form id="form1" action="">
<input type="text" name="field1" value="" />
<input type="submit" />
</form>
<div id="div1"></div>
</body>
</html>
html
<form id="frm">
<input type="button" onclick="fn()" value="Submit to function"/>
</form>
javascript
function fn(){
var frm = document.getElementById("frm");
var elements = frm.elements;
var len = elements.length;
// do something with elements
for(var i =0; i < len; i++){
console.log("%s = %s", elements[i].name, elements[i].value);
}
}

Categories

Resources