Page Redirection - javascript

I'm working on a script where all I want it to do (right now) is redirect the user based on which button they press. Eventually it will take form input and incorporate that into the redirect, but right now I'm just trying to get the buttons to send the user off to the appropriate site. However, My redirects aren't working.
<html>
<head>
<title>
Home
</title>
</head>
<body>
<script type="text/javascript">
<!--
var textstring;
var btnWhichButton;
//Gets the text from the form
function getQ() {
textstring = document.forms['Search'].elements[0].value;
}
//Does a Google Search
function googleSearch() {
window.location ="http://www.google.com";
}
//Does a YouTube Search
function youtubeSearch() {
window.location = "http://youtube.com";
}
//Figure out which button was pressed
function whichButton() {
if (btnWhichButton.value == 'Google Search' ) {
googleSearch();
} else if (btnWhichButton.value == 'YouTube Search' ){
youtubeSearch();
}
}
//main function to run everything
function main() {
getQ();
whichButton();
}
// -->
</script>
<form name="Search" >
<input type="text" name="q" size="31" maxlength="255" value="" />
<input type="submit" value="Google Search" onclick="btnWhichButton=this; main();" />
<input type="submit" value="YouTube Search" onclick="btnWhichButton=this; main();" />
</form>
</body>
</html>
When either button is clicked, the page just reloads with ?q= appended to the url, it doesn't redirect. Any help?

You want to use a button not an input type='submit'. Your current buttons are submitting the form, not performing their onclick actions.
Or block the submit action in some way. Or you could use your functions to set the form action to the url and just let it submit.

Your scripts seem highly overcomplicated. Why not have three functions: getQ, googleSearch, and youTubeSearch? Then inside the onClick event you can call the exact function, including this.value inside the input parameters and calling getQ from inside that function? Your method seems highly inefficient. If you're going to have separate functions for each of them anyways, there's no use in going through two other functions in order to get to them.
A submit button will always submit the form without a return false at the end of the onClick event, and since the default posting method is GET, its attaching ?q= to the end of your URL because that field is blank and it's the only input field in the form.

For redirecting to new page you no need to use the big javascript function.
<html> <body>
<input type="button" value="Google Search" onclick="javascript:window.location.href='http://www.google.com'" />
<input type="button" value="You tube Search" onclick="javascript:window.location.href='http://youtube.com'" />
</body></html>
Please check whether it helps you.

Well as jasonbar says, change your input to be of type 'button' and not 'submit'. Plus, I'd rather use window.location.href instead of window.location only. I don't know possible this is good practice...happy programming.

Related

Multi Scenario Form Action (Background, Multiple Actions, Timer)

I have tried using methods that may work for one scenario or another in AJAX, Javascript, JQuery and PHP, but I have not found a way to achieve the correct results for my scenarios.
I have a search box text input field as :
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
There are three scenarios in which different actions need to occur:
On page load, send the input to search-api.php as POST every 5 seconds in the background, and get results back from the action and set the response equal to $url. (Must not only show response for first submit, but also for all changes in input when updated every 5 seconds).
When enter button is pressed, send the input as GET to https://externalaction.com/search in foreground.
When button <input class="button default" name="BtnX" type="submit" value="Search"> is pressed, send the input as GET to https://externalaction.com/search in foreground.
I know this is complicated but I have yet to find a solution that works for all three scenarios without interfering with each other, and no one online seems to have any information or questions quite like this situation.
Thank you to anyone who has any help, tips, or answers / code!
This doesn't seem too complicated, although I'm not sure why you'd want to send search queries every 5 seconds instead of on keypress? In any case it should just be using $.post() and setTimeout.
<form action="https://externalaction.com/search" method="get">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
<div id="results"></div>
<script>
$(function() {
search();
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
setTimeout(search, 5000);
}
</script>
If you're interested in using keypress instead of every 5 seconds, it would be something like this for the JS:
<script>
$(function() {
$('#field').on('keyup change', 'search');
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
}
</script>
Although in this case you don't need a named function, you could just make the search() function the keypress callback.
You also mentioned wanting to set the AJAX response to $url, however that looks like a PHP variable, so you wouldn't be able to modify that if it's in the page with the form unless you reloaded it. That's easy enough to do if you wanted to programmatically do a redirect, but would get pretty tricky and into weird loops. So it would be better to know what $url is being used for in the page, and then use JS to replace it with the value from the callback the same way I'm replacing the HTML of the results div in my current example.
The search form field will submit automatically on an 'enter' keypress as long as it has focus (i.e. after someone is finished typing in it and hits 'enter'), but if you want to send results whenever enter is pressed regardless of which input has focus this answer will help.
As an aside, typically you don't want to recursively keep searching with a timeout without some kind of end condition which clears the timeout, as in some cases it can lead to memory issues.
first of all you should search input is a form and need form tag even if it's only one input. lets consider it like this:
as you set set button type to submit. the 2 and 3 options would work.
<form id="search-form" action="https://externalaction.com/search" method="GET">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
second of all in case if in some situations (really rare) some browsers didn't work properly with type="submit" for enter button you should use jQuery like this one:
$(function() {
$("#search-form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#search-form button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
for autocomplete search you can use many exist libraries or write it yourself I recommend to read this article for an example:
http://ianlunn.co.uk/articles/ajax-search-suggest-wearehunted/
actually if you use a standard form element the only thing you are looking for is just a autocomplete search input which i believe users used to see result by typing each word instead every 5 second. but its up to you.
Edited according to your last comment:
if you have a single action for search you should at least use two different view.
to use autocomplete feature you should use ajax and if you want to have only one action or page just send an extra parameter and make a partial-view which echo result back in Json instead of a complete view which contains header and footer and ...
Function searchData() handle the AJAX request. setInterval(function(){searchData()}, 5000) section handle request search content every 5 second. If click on Enter key, then that request handle on keydown event, finally click function handle the request come through the search button.
search.php
<!--- Search field and button -->
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input type="button" name="search" id="search" value="Search"/>
<!--- Display result -->
<span id="res"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
// function used for AJAX call
function searchData(){
var txt = $("#field").val();
$.get("searchData.php", {search: txt}, function(result){
$("#res").html(result);
});
}
// search every 5 second
setInterval(function(){searchData()}, 5000);
// if press enter button search
$('#field').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
searchData();
}
});
// if search button press
$("#search").click(function(){
searchData();
});
});
</script>
searchData.php - Page used to handle the request
<?php
// testing purpose
echo $_GET['search'];
?>

how do i trigger a button with the enter key in java script?/ how to give text box and search button an ID?

Sorry i know this question has been asked and answered before but i can't seem to implement it into my code. very new to programming and struggling quite a bit.
Pretty simple stuff here i have a search bar and a search button. What i am trying to do is instead of having to physically click the search button to search for what i want, i would like to have the ability to be able to click the enter key which could search as well. Here is the code for the search bar and button.
Easy stuff.
<div class="ui-widget"> <!-- only for css purposes-->
<input id="search"> <!-- for the search box-->
<button type="button" onclick="searchresult()">Search</button> <!-- search button-->
</div>
So at the moment when you click the search button it will activate the javascript function i have which is:
function searchresult() {
//find the result
}
which in turn will find the result you want. deadly stuff.
I haven't included the code which is inside the javascript function as we don't need it for this question and its quite lengthy.
so basically i want the enter key to be able to activate the searchresult javascript function the same way the search button does.
I am aware that you can use jQuery keypress() Method to do this. and here is the code which can be used to do what i am wondering but i just don't know how to implement it into what i have:
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});
I am aware of the id attribute which is used in HTML coding as well but i don't know how i would go about correctly assigning the search button and text box an id each which then i could use in the code i have just above which then in turn would allow me to use the enter key as search as well.
So if anyone could just show me how i could use the jQuery code i found to solve my question that would be brilliant. Completely open to any other suggestions about how i would go about it either.
Thank you everyone for your time and attention!
Use the following code (explanation below):
function searchresult() {
console.log('searching');
//find the result
}
$("#search").keyup(function(event) {
if (event.keyCode == 13) {
$("#searchButton").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui-widget">
<input id="search">
<button type="button" id="searchButton" onclick="searchresult()">Search</button>
</div>
What this does is it will hook up an event to the input box with the id search and whenver it receives a keyup (key release) event, it will check if it is the Enter key and, if so, fire the click event of the button with id searchButton (I added that id as an example). Your search button's click event is hooked up to the searchResult() function, which is in turn called from that.
If you need more information on how event handling works in jQuery, check out jQuery's Handling Events page.
You really should consider using a form.
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
$(function(){
$("#search").on("submit", function(e){
search_function($("#search_terms").val());
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
Or here is an example in pure JS
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("search")
.addEventListener("submit", function(e){
search_function(document.getElementById("search_terms").value);
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
}, false);
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
You can assign the id to your search button :
<button type="button" onclick="searchresult()" id="search_key">Search</button>
Then you can trigger the click action on button using jQuery#trigger
JS :
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode == 13) {
$("#search_key").trigger('click');
}
})
$('#search").change(function() {
searchResult();
});
Don't even bother with looking for the "enter" key; just watch for the input value to change (which would happen upon pressing enter, or blurring the field).
You can use a form and it's onsubmit event since you want enter key and submit click to do the same thing.
<form action="" method="" onsubmit="searchresult(this);">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
But don't forget to use event.preventDefault() or return false.

Stop double-clicking of submit button with Javascript

Here's my situation. I have a submit button. When clicked, some backend/database validation takes place and if everything's good, submit the form and disable the button so the form can't be submitted twice. If it does not pass validation, submittal cannot take place and the button stays active, so the user can resubmit the form. It sounds simple but I can't make it work. This is a C# web application.
I have tried to add the code to the button on page load. When the submit button is clicked and if validation fails, remove the code that disables the button. But here is my problem. Since the "disable" code is removed and the user fixes any error and resubmit, the button can be clicked more than one as the code is no longer there.
I do not want to use Ajax for this because the backend check is very complicated. Is there another way to do it? I've tried to add the "disable" code on "load" but it does not work on post back when the validation fails.
if (window.addEventListener)
window.addEventListener("load", lockSubmit, false);
else if (window.attachEvent)
window.attachEvent("onload", lockSubmit);
else window.onload = lockSubmit;
Any help is appreciated.
Try the snippet below
window.onload = function(){
// Insert the following function somewhere in your .js file / section
(function prevent_over_submitting(){
var form = document.forms.theform;
if(form || form.nodeName == 'FORM'){
form.onsubmit = function(){
form.submit.value = 'Proccesing...';
form.submit.disabled = true;
};
}
})();
};
While your form should look something like this one
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<input type="text" name="lastname" value="" />
<input type="submit" name="submit" value="submit" />
</form>
Here is a working jsBin so you can play around.
Update:
The logic behind the snippet above
// server-side code (rather in pseudo-code this time)
if(form_has_been_submitted){ // check if the form has been submitted
errors[] = validate_data(post_data); // call the method to validate data
if(errors_array_is_empty){ // if everything is fine
submit_data(); // submit data
redirect_or_do_something; // (maybe) do other things
} // otherwise don't do anything
}
// validation method
validate_data(post){ // the only argument here represents all your form data
error = array;
if(post['firstname'] == wrong){ // check for error
error['firstname'] = 'Check your firsname'; // if you found one, push it to the error array
}
if(post['lastname'] == wrong){ // the same as in previous case
error['lastname'] = 'Check your lastname'; // the same as in previous case
}
return error; // return that array, it might be full or empty
}
// client-side code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyApplication</title>
<script type="text/javascript">
// the JavaScript snippet from above
</script>
</head>
<body>
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<!-- show the error if you found one, otherwise show an empty string -->
<span><% (error['firstname'] ? error['firstname'] : "") %></span>
<input type="text" name="lastname" value="" />
<!-- same as in the previous case -->
<span><% (error['lastname'] ? error['lastname'] : "") %></span>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
As you can see, the JavaScript snippet above only disables the submit button onclick to prevent over-submitting; it will be enabled once the page is loaded again. This isn't my favorite way of validation but I followed your logic.
you can add this code in the onclick function:
First, add a global javascript variable, say var click = false;
and add this condition before validation occurs:
if(click){
return false
} else {
your normal validation code
}
if your page reloads each time you submit, then there is no need to add anything further, but if doesn't then add setInterval method which will reset the click variable for next use if validation fails.
The state of the click variable will remain true after first click and will further stop multiple clicks, unless page reloads or we reset the variable manually through code.

two submit buttons, with confirmation pop up only on one submit button

I have two submit buttons in a form that Lets user Update/ Delete content. I want a confirm pop only if the user clicks Delete button.
<html>
<head>
<script type="text/javascript">
function confirmation() {
// I need to know which submit button was pressed.
if (value==Delete){
var answer = confirm("Cancel?")
if (answer){
return true;
//Continue as intended
}
else{
return false
}
}
}
</script>
</head>
<body>
<form id="Edit_Data">
//form input fields go here
<input name="action" type="submit" onclick="confirmation()" value="Update">
<input name="action" type="submit" onclick="confirmation()" value="Delete">
</form>
</body>
</html>
Any Ideas?
First of all you have several problems with your code. The value in your if statement is an undefined variable secondly you need to put quotes around the delete. Here is working fiddle http://jsfiddle.net/SMBWd/ and the relevant code change. Also, I would encourage you to look how to do this without using javascript in your HTML.
function confirmation(e) {
// I need to know which submit button was pressed.
if (e.value=='Delete'){
and in the HTML
<input name="action" type="button" onclick="confirmation(this)" value="Update">
<input name="action" type="button" onclick="confirmation(this)" value="Delete">
For your onclick event definition in the html tag, why not call separate functions?
The simplest way would be to NOT call the javascript on the Update button.
If your form is static, then you do this in your IDE. If it's dynamic, then the dynamic code can create the form element accordingly.
If the form elements are generated automatically, then you should setup an event handler in JavaScript dynamically. Find all elements of type input with type attribute button or submit, and assign
elems[i].onclick = confirmation;
You'd then get the event object as a method parameter, and you could query that for the value of the button.

Can server script detect if a form is posted with submit button or with javascript:Submit()

This problem is keeping me busy all week and I find little to nothing on the net ...
What I want to do is simple ... on my own website, create a server side PHP script that makes a login to another website with valid credentials and downloads a file that I want to process.
I use curl_init(), curl_setopt() and curl_exec() in trying to achieve that. It doesn't work.
So I stripped down that webpage to figure out what's wrong.
As you can see in the html code, the form's action event is the url to retrieve the file, when correct credentials are submitted.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form name="form1" method="post" action="http://otherwebsite/login.aspx?ReturnUrl=/export_file.aspx?id=xxxxxxx" >
<script type="text/javascript" language="JavaScript">
function Submit_Form()
{
document.form1.Login$UserName.value="myname";
document.form1.Login$Password.value="mypassword";
//document.form1.Login$LoginButton.click();
document.form1.submit();
}
</script>
<input type="hidden" name="Login$UserName" value="myname" />
<input type="hidden" name="Login$Password" value="mypassword" />
<input name="Login$LoginButton" type="submit" />
<br />Login
</form>
</body>
</html>
Now here is where it gets weird.
If I press the button, it works and I receive the download file.
If I click the hyperlink, i get a page saying to login properly.
When I uncomment the javascript line : click() it works too.
So it comes down to this :
Why does the button submit work and javascript submit doesn't work ?
Is there a way that the other website's server check how the form was posted ?
Thank you for your thoughts !
When you click the button, its name is included in the POST request because it's a named submit button. When you use the link, the button's name doesn't get passed in the POST data.
You could probably spoof the button when you use the link by having a hidden field with the name the button should have:
<input type="hidden" name="Login$UserName" value="myname" />
<input type="hidden" name="Login$Password" value="mypassword" />
<input type="hidden" name="Login$LoginButton" />
Note it doesn't need a value because the button it replaces doesn't have a value setting its text. Just including it should be sufficient.
Why not have another hidden field called js_submitted with a value of false, and in your Submit_Form() function, set it to true before firing the submit() method? Then, in PHP (for example), you could look for $_GET/$_POST['js_submitted'] to determine which submission method was used.
It's possible to check that the button was posted with the submit. Maybe they are checking for this.
Yes, it is very easy to find out when a button submits a form, and that is exactly what the site might be doing.
A button is a form control and so, when a form is submitted, the button state is submitted as well. What this means is, when you check the form object on the server that receives the post, you will see it contains a key with the same name as the button and it's value is set to the value attribute of your button.
Consider you have a form:
<form id="form1" action="abc.asp" method="post">
<input type="submit" name="btn" value="Opt123" />
<input type="submit" name="btn" value="Opt456" />
Send
</form>
I am not a PHP person, so code might not be the best:
$item = $_POST['btn'];
In this case, value of $item will be either Opt123 or Opt456 depending on the button pressed, whereas if the link is pressed, then it would be a null or PHP equivalent.
Even though the submit button is part of the form, the browser only sends its name=value pair as part of the post data if the button was actually clicked. When you call the .submit() method from Javascript, your browser sends the data Login$Username=myname&Login$Password=mypassword to the server. But when you actually click the button, it sends Login$Username=myname&Login$Password=mypassword&Login$LoginButton=. As you can see, it would then be very easy for the server to differentiate between the two.
So, you can trick the form into always sending that element by making it hidden. In Submit_Form, just before you say document.form1.submit();, add this:
var sbtn_hid = document.createElement('input');
sbtn_hid.type = 'hidden';
sbtn_hid.name = 'Login$LoginButton';
sbtn_hid.value = '';
document.form1.appendChild(sbtn_hid);
That adds a hidden form element with the same name as the submit button, so the server won't be able to tell the difference.

Categories