JavaScript redirect on form submission - javascript

I'm trying to do an exercise that will allow users to be redirected to a specific local web page based on their search term. For some reason, window.location.replace will not redirect. I tried a variant of window.location that opened the landing page in a new tab, which worked. Any help is appreciated!
html
<form name="form1" onsubmit="myFunction()">
Street Address:
<input type="text" id="streetaddress" required="true"><br>
Township:
<input type="text" id="township" required="true">
<br>
<input type="submit" onclick="return myFunction()" name="Search" value="Search">
</form>
<p id="demo"></p>
js
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "";
var nameValue1 = document.getElementById("streetaddress").value;
var nameValue2 = document.getElementById("township").value;
if (nameValue1.toUpperCase() === "1 MARJORAM DRIVE" && nameValue2.toUpperCase() === "LUMBERTON") {
window.location.replace("landingpage.html");
}
else {
document.getElementById("demo").innerHTML = "<font color='red'><p>0 results</p></font>";
return false;
}
}
</script>
Update
I have modified my code implementing suggested solutions but am still encountering the same issue where the page won't redirect. Lines I've changed from original code are below...
html
<form name="form1" onSubmit="return myFunction()">
<input type="submit" name="submit" class="submit" value="Search">
js
if (nameValue1.toUpperCase() === "1 MARJORAM DRIVE" && nameValue2.toUpperCase() === "LUMBERTON") {
window.location.href = 'landingpage.html';
}

Just change the window.location variable
window.location = "http://www.newsite.com/path/to/page";
For a page that is locally hosted use the following:
window.location.href = "newlocation.html";

Related

Can't go to a url in javascript

I am a total noob to web programming (Started just now). I know C, C++ and x86-assenbly (a little bit). I wanna create my own home page for my browser. It's very basic html for the most part but I want a search bar on the top that redirects to duckduckgo with relevant results and that's where the problem arises. The code I'm trying:
<form>
<input type="text" id="query"/>
<button id="button" class="button" onclick="openInDuck()">Search</button>
</form>
<script>
function openInDuck(){
var x= "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location = x;
}
</script>
And yeah, I forgot, I am using qutebrowser on archlinux if that matters. Thanks in advance.
You are missing .href on your redirect. Also you should change the button type to button instead of the default;
function openInDuck() {
var x = "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location.href = x;
}
<form>
<input type="text" id="query" />
<button id="button" class="button" onclick="openInDuck()" type="button">Search</button>
</form>
Do note that it wouldn't be ideal to redirect the user if you just need to do a search through a different api.
You can use the below
function openInDuck() {
var x="https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.open(x);
}
Problem is that your form is submitted when clicking the button, like this it works :)
<input type="text" id="query" />
<button id="button" class="button" onclick="openInDuck()">Search</button>
<script>
function openInDuck() {
var x = "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location = x;
}
</script>
You are close to the solution. In the JS code, you must add .href after window.location to set the new href (URL) for the current window. In the HTML code, I suggest you use the onsubmit attribute to send the form with an input type="submit" :
function openInDuck()
{
var x = "https://duckduckgo.com/?q=";
x += document.getElementById('query').value;
window.location.href = x;
return false; // Prevent the form submission
}
<form onsubmit="return openInDuck()">
<input type="text" id="query">
<input type="submit" id="button" class="button" value="Search">
</form>

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

Make a submit form that uses its input to determine a link

I want to make a form that upon submitting, opens a html file that uses the users submission at the end of the url in the same tab.
Ex. Submit=link1, Opens code.html/link1 (same window)
As of now, putting, "_self" after window.open("code.html/" + s... just makes the url have a question mark at the end, which I'm told it is because of the GET method.
(Javascript)
<script>
var s = document.getElementById("submit").value;
function doFunction(){window.open("code.html/" + s);}
</script>
(HTML)
<form onsubmit="doFunction()">
<input id="submit" type="text" />
</form>
Perhaps you can try this:
<form onSubmit="return doFunction();" target="_self">
<input id="text-value" type="text" >
<input type ="submit">
</form>
I also added submit button.
<script type="text/javascript">
function doFunction(){
var s = document.getElementById("text-value").value;
var url = "code.html/" + s;
var win = window.open(url, '_self');
return false;
}
</script>

JavaScript is not redirecting

My Javascript is not redirecting. Here is what I tried:
<html>
<head>
<title>Hello world</title>
</head>
<body>
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="processFormData()">
</form>
<script>
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
}
</script>
</body>
</html>
I want user to be redirected to a specified url no matter of the url in browser. This should be universal on different machines. I am new to JS, please advise.
First, move the onclick event handler declaration to the <form> tag. Next, change it into an onsubmit event handler declaration. Finally add a return in front of it (to prevent default event handling, i.e. actually submitting the form):
<form method="POST" onsubmit="return processFormData();">
Search: <input id="searchterm" type="text" name="searchterm" />
<input type="submit" value="Submit" />
</form>
Then also add a return false; at the end of processFormData:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
return false;
}
Fiddle here: http://jsfiddle.net/xwcvq7bf/
Use location.host. Try this:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = "http://"+location.host+"/"+term;
return false;
}
And,
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="return processFormData()">
</form>
So, now your url will be like this: http://www.example.com/searchTerm
You can specify the url itself,
window.location = "url"+term;
If you wanna get only the hostname(http://www.example.com),
window.location = location.hostname +"/"+term;
or If you wanna get the href(http://www.example.com/home/about.htm),
window.location = location.href +"/"+term;

I can't post to google?

Here is the code for a small program where you put the keyword, choosing the search engine and then pressing "Search" button to search. But google don't leave me to POST. What else I can do?
EDIT: Yahoo and Bing works fine.
ERROR
405. That’s an error.
The request method POST is inappropriate for the URL
/search?q=computer. That’s all we know.
HTML
<form name="search" action="" method="Post" onSubmit="redirect()">
<input type="text" name="keyword"><br />
Google<input type="radio" name="ch" checked>
Yahoo!<input type="radio" name="ch">
Bing<input type="radio" name="ch"><br />
<input type="submit" value="Search">
</form>
Javascript
<script type="text/javascript">
var searchengine=[
"http://google.com/search?q=",
"http://search.yahoo.com/search?p=",
"http://bing.com/search?q="
];
function redirect()
{
var radioButtons = document.getElementsByName("ch");
for (var x = 0; x < radioButtons.length; x++) {
if (radioButtons[x].checked)
{
document.search.action = searchengine[x] + document.search.keyword.value;
}
}
}
</script>
But google don't leave me to POST. What else I can do?
Use GET rather than POST in your form, or just assign the relevant URL to window.location.
Here's an example of the latter. Some other changes:
Added some labels.
Changed how you're matching up the selected radio button and the searchengine to make it more robust/maintainable.
Changed the name of the search form. Since this gets dumped on the window object I avoid simple words like "search".
Properly encoded the keyword (you must encode URI parameters).
Live copy | Live source
HTML:
<form name="searchForm" action="" method="GET" onSubmit="return doSearch()">
<input type="text" name="keyword">
<br>
<label>Google<input type="radio" name="ch" value="google" checked></label>
<label>Yahoo!<input type="radio" name="ch" value="yahoo"></label>
<label>Bing<input type="radio" name="ch" value="bing"></label>
<br>
<input type="submit" value="Search">
</form>
JavaScript:
var searchengine = {
"google": "http://google.com/search?q=",
"yahoo": "http://search.yahoo.com/search?p=",
"bing": "http://bing.com/search?q="
};
function doSearch() {
var frm, index, cb;
frm = document.searchForm;
if (frm && frm.ch) {
if (frm.ch) {
for (index = 0; index < frm.ch.length; ++index) {
cb = frm.ch[index];
if (cb.checked) {
window.location = searchengine[cb.value] +
encodeURIComponent(frm.keyword.value);
}
}
}
}
return false; // Cancels form submission
}
"http:google.com/search?q=", is not formatted properly..
try "http://google.com/search?q="

Categories

Resources