I'm trying to redirect a user to another page after clicking on a form submit button.
I'm trying to fire a few events which fill in certain parts of the form automatically then submit the form & finally redirect the user to another page.
Everything works expect the redirect. I have tried a few things but havent gotten the redirect to work after the form submits.
I also don't want to user to be redirected before the form has been successfully submitted.
Here is my code:
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
<input class="usp_input" type="text" name="user-submitted-url" id="user-submitted-url" value="">
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input class="usp_input" type="text" name="user-submitted-category" id="user-submitted-category" value="">
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
<input class="hidden" type="hidden" name="user-submitted-name" value="<?php echo $current_user->user_login; ?>">
<input onClick="copyText();copyText2();copyText3();handleClick();" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
<script language="javascript" type="text/javascript">
function copyText3() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-title").value = output1 + ', ' + output2;
}
</script>
<script language="javascript" type="text/javascript">
function copyText2() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
var output3 = document.getElementById("template").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + ', ' + output2 + ', ' + output3;
}
</script>
<script language="javascript" type="text/javascript">
function copyText() {
var output = document.getElementById("templatebody").innerHTML;
document.getElementById("user-submitted-content").value = output;
}
</script>
<script language="javascript" type="text/javascript">
function handleClick() {
window.location.href='http://website.com/';
}
</script>
The submit button will launch a request, but you are also defining a redirecting request on the button press, so one will override the other (I'm not sure which one, it may depend on the browser).
You may want to fire an Ajax request instead of the standard submit, and do the redirection only when you get the response from the Ajax request so you are sure no information was lost.
You should not code like is but register your functions on the event, outside de HTML (it's always better to separate your HTML, JS and CSS).
You can understand about events bubling here : http://javascript.info/tutorial/bubbling-and-capturing
If you just want to see your code working and don't validate your form, just add "return false ;" at the end of your onclick attribute.
Edit : Oups sorry, you want submit your form, then redirect. You can do this with ajax requests (see http://www.w3schools.com/xml/xml_http.asp) : you submit your form in ajax, then you redirect.
But IMO, It's a serverside behaviour : you probably have a dynamic language (Python, PHP, ASP... ?) which process your form submission. It's here you have to redirect after the process.
Related
I'm creating a simple website and a html page on it which contains a table that shows products. I load this table using AJAX and it work properly. Here is a screenshot:
Under the table I have buttons which perform CRUD operations using AJAX.
They communicate to a php script on a server outside of my domain using GET method.
When I click on Add product it opens a form with a button that whose onclick event calls a function which adds a product using AJAX. But, when I click, the whole page reloads and the product is not added. If I put the value that says wheter the call is async to false, it works as intended and the product is added to the table, however that is not the point of AJAX.
This is my code for adding a product(delete and update are almost the same).
<div id="addProductPopup">
<div id="popupContact">
<form id="form" method="post" name="form">
<img id="close" src="/servis/Resursi/Slike/close.png" onclick ="hide('addProductPopup');">
<h2>Dodavanje proizvoda</h2>
<hr>
<input id="name" name="naziv" placeholder="Naziv proizvoda" type="text" required>
<input id="kolicina" name="kolicina" placeholder="Količina proizvoda" type="text" required>
<input id="url" name="url" placeholder="URL slike" type="text" required>
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct()">
</form>
</div>
When I click on submit this function is called:
function addProduct(){
var isValid = true;
var url = "http://zamger.etf.unsa.ba/wt/proizvodi.php?brindexa=16390";
var amount = document.form.kolicina.value;
var naziv = document.form.naziv.value;
var slikaurl = document.form.url.value;
var validity = validateFields(naziv, slikaurl, amount);
if(!validity) return false;
var product = {
naziv: naziv,
kolicina: amount,
slika: slikaurl
};
var requestObject = new XMLHttpRequest();
requestObject.onreadystatechange = function(event) {
if (requestObject.readyState == 4 && requestObject.status == 200)
{
loadProducts();
event.preventDefault();
}
}
requestObject.open("POST", url, true);
requestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
requestObject.send("akcija=dodavanje" + "&brindexa=16390&proizvod=" + JSON.stringify(product));
}
It is because you are not preventing the default action of the submit button click.
You can return false from an event handler to prevent the default action of an event so
<input type="submit" value="Pošalji" class="popupButtons" onclick="addProduct(); return false;">
But since you have a form with a submit button, I think it will be better to use the submit event handler like
<form id="form" method="post" name="form" onsubmit="addProduct(); return false;">
....
<input type="submit" value="Pošalji" class="popupButtons">
Your problem is that your submit button still executes a real submit. You could change your addProducts method. The method have to return false to prevent the real submit.
Submit button performs default Submit action for HTML code.
Try to change Submit tag into Button tag. Or after AddProduct() in OnClick JS Action put
return false;
Simple Change put input type="button" instead of tpye="submit"
<input type="button" value="Pošalji" class="popupButtons" onclick="addProduct()">
I have an input which on submit is redirecting to another page and i want this page to redirect to another using form input:
<form id="composeLink" method="post" name="composeLink" action="{$address}/" >
<input type="hidden" name="username" value="{$fields['username']}" />
<input type="hidden" name="password" value="{$fields['password']}" />
<input type="hidden" name="login" value="1" />
</form>
<script type="text/javascript">
//document.form.action = document.form.action.replace("http","https");
document.getElementById('composeLink').submit();
</script>
Action method of this form is send using smarty. The problem is that the link is not correct. Eg: current link is http://test.com and form action is http://action.com and the redirecting page has the link combined.
LE: the action form is send correctly
What can be the problem?
Problem is on your template engine, there is no problem, i mean on html. But you can write a javascript and solve that problem. If your action generated like that ( test.com/http://action.com ), please write this one :
<script type="text/javascript">
var newAction = document.getElementById("composeLink").action.split("http://");
document.getElementById("composeLink").action = "http://" + newAction[1];
document.getElementById('composeLink').submit();
</script>
If your action generated like that ( http://test.com/http://action.com ), please write this one :
<script type="text/javascript">
var newAction = document.getElementById("composeLink").action.split("http://");
document.getElementById("composeLink").action = "http://" + newAction[2];
document.getElementById('composeLink').submit();
</script>
The different is your generated URL, if there is two "http" on your URL (For split), you have to use last code as i wrote
SO I have a form that look similar to
<form action="test.php" id="checksub" method="post">
<div>
<select name="mydropdown">
<option value="buy">buy</option>
<option value="sell">sell</option>
</select>
</div>
autocomplete text input that triggers "checksub"
<input type="submit" id="checksub" name="checksub" style="visibility:hidden">
<input type="submit" id="newsbutton" name="newsbutton">
</form>
<script type="text/javascript">
$('#newbutton').click(function() {
var newaction = "cantfinditems.php";
$("#checksub").prop("action", newaction);
$('#checksub').submit();
});
</script>
Now the submit button is hidden because the autocomplete triggers it anyway, but if the user cant find what they are looking for I want a button that says "cant find what your'e looking for?"
I want this button to have a different action to the form action, ie window.location = cantfinditems.php
but I also want to carry the POST data from the form ie "mydropdown".
Thank you
Ok, so you need a second button, which calls a JavaScript function. In this function, you do a number of things:
Set the action attribute of the form to your alternate action (e.g. cantfinditems.php)
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);
Submit the form
$('#form_id').submit();
So a full example would be:
<script type="text/javascript">
$('#yourbuttonid').click(function() {
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);
$('#form_id').submit();
});
</script>
I want to submit a form. But before that I wanna validate it. The validation is a javascript method. everything is ok as long as the javascript method is in the same .jsp file as the form.
But I want to put it to an external javascript file, and the method gets never called. Why?
this part should include the javascript into .jsp file.
<script type="text/javascript" src="Validate.js">
var val = new Validate();
var result= val.validateArticle();
</script>
here is the form I want to submit:
<form name="articleAnswerForm" action="answer.html"
action="answer.html" onsubmit="return result" method="post">
Was is der Artikel?<br> <select name="art">
<option>???</option>
<option>der</option>
<option>die</option>
<option>das</option>
</select> <input type="hidden" name="richtig" value="${selected.article}">
<h1>${selected.german}</h1>
<input type="submit" value="Antworten">
</form>
The Validate.js is in the same directory as the .jsp file.
here is the Validate.js (but it works fine, if it is in the .jsp file.)
function validateArticle() {
var a = document.forms["articleAnswerForm"]["art"].value;
var richtig = document.forms["articleAnswerForm"]["richtig"].value;
if (a == null || a == "" || a != richtig) {
alert("Nein " + a + " ist falsch");
return false;
}
}
so far the only thing that works is if I put everything into one .jsp file like below
<script type="text/javascript" >
function validateArticle() {
var a = document.forms["articleAnswerForm"]["art"].value;
var richtig = document.forms["articleAnswerForm"]["richtig"].value;
if (a == null || a == "" || a != richtig) {
alert("Nein " + a + " ist falsch");
return false;
}
}
</script>
<form name="articleAnswerForm" action="answer.html"
action="answer.html" onsubmit="return validateArticle()" method="post">
Was is der Artikel?<br> <select name="art">
<option>???</option>
<option>der</option>
<option>die</option>
<option>das</option>
</select> <input type="hidden" name="richtig" value="${selected.article}">
<h1>${selected.german}</h1>
<input type="submit" value="Antworten">
</form>
<form:form method="post" action="word.html">
<input type="submit" value="nächste Wort">
</form:form>
</c:if>
First, you cannot mix a src-ref and local code in one script tag.
<script type="text/javascript" src="Validate.js"></script>
<script type="text/javascript">
var val = new Validate(); // 'new Validate' won't work.
var result= val.validateArticle();
</script>
In HTML, onsubmit="return result" will probably not do what your are intended to. You want to validate on submit, won't you? So you have to call the validateArticle() function then, not on page load. And there is no need to instanciate a Validate object.
onsubmit="return validateArticle()"
This is all you need. You don't need to create an instance to use the Validation function.
Script:
<script type="text/javascript" src="Validate.js"></script>
HTML Form:
<form name="articleAnswerForm" action="answer.html"
action="answer.html" onsubmit="return validateArticle()" method="post">
Was is der Artikel?<br> <select name="art">
<option>???</option>
<option>der</option>
<option>die</option>
<option>das</option>
</select> <input type="hidden" name="richtig" value="${selected.article}">
<h1>${selected.german}</h1>
<input type="submit" value="Antworten">
</form>
So when you are moving Javascript to an external file. You don't need to do anything special to access it. There is no instantiation required. Just use the javascript as you would if it was included in the file itself. If you find it doesn't work, it's likely the file isn't loading properly, in which case check the file is in the right directory and the case of file is correctly set, as some file system are case sensitive.
I've just started JavaScript and I am facing a problem. I've written a script in which I am calling a function. I don't know why this script is calling itself twice.
The code is as below:
<html>
<head>
<script type="text/javascript">
var randomNo1 = Math.floor(Math.random()*10);
var randomNo2 = Math.floor(Math.random()*10);
window.onload = ask;
function ask()
{
alert("How much " + randomNo1 + " times " + randomNo2 + "?");
}
function question()
{
var product = randomNo1 * randomNo2;
var stdAnswer = document.getElementById('answer').value;
if(stdAnswer == product)
{
alert("Very good!")
//generate new nos
randomNo1 = Math.floor(Math.random()*10);
randomNo2 = Math.floor(Math.random()*10);
ask();
}
else
{
alert("No. Please try again.");
ask();
}
}
</script>
</head>
<body>
<form>
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>
</body>
</html>
Add action="#" to your form, to avoid page being refreshed when form is submitted.
<form action="#">
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>
You call it twice, once at startup window.onload = ask; and once in question
[edit]
note too that you don't have a ; after the first alert() in question()
[/edit]
Because your button is a submit button. When clicked it runs click handlers (if specified), then posts the form. So you call ask() twice. One time in a click handler, and another time in a window.onload handler.
After this form is submitted, page simply reloads (because it has no associated action). And onload handler is fired again.
You can see it here: http://jsbin.com/ukusof.
Your form as no method nor action. When you click your submit button, the page refresh itself, thus firing ask again.
You're submitting the form, which loads the page again, so ask will be fired again on load.
You have a form with a submit button. With no action in the form, it resubmits the page. You can stop this with
<input type="submit" value="Check" onClick="question();return false" />