I'm trying to submit the document (return_url) only after the countdown finishes. In my current code below the document is submitted just after the countdown starts. How can I make the countdown finish before submitting the document_url?
Code:
<body>
<center>
<form name="redirect"><font face="Helvetica"><b>
Thank you! You will be redirected in<input type="text" size="1" style="font-size:25px" name="redirect2">seconds.</b></font>
</form></form>
</center>
<form name="return_url" method="post" action="confirm.php">
<input type="hidden" name="order" value="1" />
<input type="hidden" name="price" value="100" />
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
var targetURL="<?php print_r($_POST['url_retorno']);?>"
var countdownfrom=10
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=1){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
} else {
window.location=targetURL
return
}
setTimeout("countredirect()",1000)
}
countredirect()
document.return_url.submit()
</script>
Big point, you shouldn't automatically submit forms for users, it's kind of a bad UX design. Instead, you could do the wait before submiting thing which disables the button until the timer is up. And for that, you just need to make use of javascript timers.
var timer = window.setInterval(updateClock,1000);
var countdown = 10;
function updateClock() {
countdown--;
if(countdown<=0) {
window.clearInterval(timer);
//ALLOW THE FORM TO SUBMIT
document.getElementById("elementID").disabled = false
} else {
document.getElementById("elementID").value = "PLEASE WAIT "+countdown+" SECONDS";
}
}
I'm also adding in a side point that you should never trust what people put into forms. Lookup XSS or cross site scripting, and SQL injection to find out why. So you need to use validation (even for numbers). If you want on page validation (which still isn't really secure since it can be by-passed) you could add a onSubmit="validate()" attribute to the form tag to call the validate() function when the user does finally submit it. Using this function also gives you the power to take over the form if needed, since you can execute any javascript you want there and simply returning a "false" value will cause the form to NOT submit.
ALWAYS VALIDATE YOUR FORM ENTRIES ON THE SERVER LEVEL (ie. in the confirm.php file)
Try the following:
setTimeout(function() {document.return_url.submit();}, 10000);
That should be all you need.
Or if you want to display the timer, use setInterval();
var seconds_left = 10;
var timer = setInterval(countdown, 1000);
function countdown() {
seconds_left--;
if (seconds_left) {
console.log(seconds_left); //or modify the DOM
} else {
document.return_url.submit();
clearInterval(timer);
}
}
Related
I want to add a sound when the submit button in my form is pressed, but no matter what I do, the sound doesn't finish. It is 1 second long, but the form is submitted under 1 second, so it sounds really bad. This is the code:
Creating the sound:
<script type="text/javascript">
var html5_audiotypes={
"mp3": "audio/mpeg"
}
function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}
}
}
var mouseClick=createsoundbite("sounds/cashSound.mp3")
</script>
HTML:
<form method='post' action='save.php'>
<input type='submit' name='apply' value='Play' onclick='mouseClick.playclip()' />
</form>
I tried the setTimeout function but it didn't work! Any suggestions?
Try to return false in playClip function. This may cause, the submit action will not be performed. You can wait for one second and call submit() on form element. You can also send form by AJAX.
Leaving aside the aesthetics, if you really want the sound to finish, then you'll need to delay submission / delay the response or play the sound in a seperate frame, one which is not embedded within the same page as the form.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript post request like a form submit
I have a value calculated in JS that I'd like to pass as part of an input form to a PHP script. How can I get a value the JS value to the PHP as a POST parameter?
Basically, on submit, I need the total var to be passed via post to the next script.
The first idea that comes to mind is create an invisible input form that has the value in it and is inputted with the form, is that possible?
There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.
create this form element inside your form:
<input type="hidden" name="total" value="">
So your form like this:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
Click to submit
</form>
Then your javascript something like this:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.
You can do this using Ajax. I have a function that I use for something like this:
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.
Your idea of an hidden form element is solid. Something like this
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
Of course, this will change the location to script.php. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required
$.post("script.php", { total: getTotalFromSomewhere });
This has got to be easier than I'm making it. I ahve a form that has an onclick action, it runs js that submits the form value to another page. How do I allow users to press return to perform the same action? I've tried some onkeypress stuff, but nothing has worked. Below is the form, and the js being run.
Thanks!
**updated code to reflect more of what I am trying to do..
<script type="text/javascript">
function getQueryValue(name) {
var match = (new RegExp('[?&;]' + name + '=([^&;#]*)')).exec(document.URL);
return match ? unescape(match[1]) : null;
}
var ext = "&ext="+getQueryValue('ext');
</script>
<script src="prototype.js"></script>
<script type="text/javascript">
function checkSubmit(e)
{
if(e && e.keyCode == 13) // if key is enter
{
doSubmit(); // call your submit function
}
}
</script>
</head>
<body>
<div id="dialNumber_form">
<form id="dialer" style="margin-bottom:0;">
<input id="numberBox" name="outnumber" onKeyUp="checkSubmit(event)" type="text">
<input id="submitButton" onsubmit="dosubmit()" type="button"/>
</form>
<div class="clear"></div>
</div>
<div id="success">
</div>
<script type="text/javascript">
function dosubmit( ) {
var par = $('dialer').serialize();
var url = par + ext;
new Ajax.Updater('success', 'dial.php', { method: 'post' , parameters: url , evalScripts: true } );
$('dialer').reset();
}
</script>
</body>
dial.php is taking the number you enter in the field, checking that it's valid, and sending it to our PBX to be dialed. This works, assuming you click the submit button. If you press return (even with the updated code, as recommended below), the page refreshes, and the contents of the outnumber box are posted as GET URL variable, rather than being sent to the dosubmit action. When the form works, you see it stay as it was originally built (dialout.htm?ext={extension number})
Thanks for all the responses. Let me try some of your suggestions, and I'll get back to you.
Not sure I'm clear in what I need to accomplish. This entire thing is being run in an iframe that is passed URL variables. I have no control over that piece, so I need to work with what I've got. When a user opens it, the URL would look something like .../dialout.htm?ext=1234. The extension is used, along with the number entered into the outnumber box, to place a call (system dials extension first, then outnumber). They should be passed to dial.php for processing, and if everything is good, a success response is sent back with the results (and the call is made). This works great if the dial button is clicked. The page does not refresh, and after a short delay, the success box pops up and a call is placed. If enter is pressed, the form refreshes, and the URL changes to .../dialout.htm?outnumber=<number>. I want enter to do what clicking the dial button does. Nothing i've tried here really works for that (unless I'm just really slow..). Any ideas?
You should make your submit button <input type="submit" id="submitButton" etc> then attach an onsubmit handler. jQuery:
$("#dialer").submit(function() {
var result = doMyStuff();
if (result > 10) {
return false; // prevent the submit
}
else {
return true; // allow the submit to happen
}
});
See the jQuery .submit() docs.
Returning false prevents the submit from occurring, true allows it. (I normally wouldn't put a "return false else return true" (return (result<=10);) but wanted to make the true/false sumbit control explicit)
When using AJAX to do the submit you'd want to return false so the normal submit is suppressed.
Update:
Returning false to stop default event processing is, these days, mostly deprecated. Using preventDefault() is generally preferred. This would change my example to be:
$("#dialer").submit(function(event) {
var result = doMyStuff();
if (result > 10) {
event.preventDefault(); // prevent the form submit
}
});
The keyDown / keyUp listener should be on the input not the submit button
<input id="numberBox" name="outnumber" onKeyUp="checkSubmit(event)" type="text">
function checkSubmit(e)
{
if(e && e.keyCode == 13) // if key is enter
{
doSubmit(); // call your submit function
}
}
Working example : http://jsfiddle.net/sVnMy/
This will listen to key presses on the input field and when the enter key is pressed it will submit the form
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
<input type="button" name="continue" id="continue" value="Continue" onclick="<?
if($_POST['rules']==null) {
echo "hello();";
}
elseif($_POST['rules']!=null) {
echo "myRedirect();";
}
?>" >
i have a form with a textarea. when the user hits the button when the textarea is null it should do the function hello() and if the textarea is not empty it should do the function myRedirect(). the function hello() and myRedirect() generates different dialog boxes. but it doesn't seem to work. what's wrong with this code?
It's not possible like that. JavaScript (onlick) executes in client browser while PHP executes on your server. IF you really need to execute PHP code you should use AJAX to send another request for your server to do PHP part.
If you're simply checking the value of the box, you just need Javascript... This should work fine:
<script type="text/javascript">
function check(obj_id){
var result = document.getElementById(obj_id).value;
if(result == ""){
is_null();
}else{
is_not_null();
}
}
function is_null(){
alert("null");
}
function is_not_null(){
alert("not null");
}
</script>
<input type="text" id="test" />
<button onclick="check('test')">Test</button>
Pass the id of the textbox you want to check into the check() function, and it finds whether anything has been entered into the box. If it has, it calls the function "is_null()" and "is_not_null()" if there is something in the textbox.
I think it will not work at all because you are trying to call a PHP code from javascript.
In other words PHP is a server side scripting language and you are trying to execute a server side code that needs to be submitted in order to get executed.
To achieve this functionality you can simply write this code
if($_POST['rules']==null)
{
echo "hello();";
}
elseif($_POST['rules']!=null)
{
echo "myRedirect();";
}
at the top of your PHP page and you will get what you want. or make the input type as "submit"
You probably need a postback to the server to execute whatever you want to run in the onclick event.
Another work around is to use AJAX.
Are you mixing up client side and server side? Is this what you're after?
<?php
if($_POST['rules'] == null) {
echo "hello";
} else {
myRedirect();
}
?>
<input type="submit" name="continue" id="continue" value="Continue">
<script>
function hello(){}
function myRedirect(){}
function ifnullz(el){
if($(el)!=0){
hello();
}else{
myRedirect();
}
}
function $(el){
document.getElementByID(el).length; //.value?? idk.. something like that.
}
</script>
<input onlcick="ifnullz('lolz');">
<textarea id="lolz"></ta>