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.
Related
I need to view an a simply confirm message before send a submit form.
I've an variable that contain a value to print in a popup windows.
how to insert an echo in a windows confirm()?
$('#mess').submit(function() {
var conf = confirm("you are sent the message to<?php echo $count; ?>customer, Do you want to send?");
return conf;
});
It's a much better practice to avoid mixing PHP and JavaScript. The reason being is that PHP gets executed on the server whereas JavaScript gets executed via the browser. Mixing the two could lead to some unexpected behaviour.
The much preferred method is to assign data-* attributes to a DOM element. This can be retrieved via the .attr() method jQuery has.
Below is an example of how to use:
HTML/PHP:
<div id="jsInfo" data-count="<?php echo $count; ?>"></div>
JS:
$('#mess').submit(function()
{
return confirm(
'you are sent the message to'+
$('#jsInfo').attr('data-count') +
'customer, Do you want to send?'
)
});
Here is the way I do it but you could use submit handler and do something like:
$('#yourFormButton').click(function(e) { e.PreventDefault() }
The default action of the submit button is to submit the form so you need to stop that action from happening.
An alternative and the way I use, the button on your form should be of type="button" and not submit, then use the following:
$('#yourFormButton').click(function()
{
var conf = confirm("you are sent the message to<?php echo $count; ?>customer, Do you want to send?");
if(conf){
$('#mess').submit();
}
});
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);
}
}
.net developer trying to do a php site for a friend, so far everything is going great but I was wondering if php has something like a textchanged event. Here is what I want to do, I want a drop down box to be appended with data retrieved from a database based on what the user enters in a textbox above(Using the text in the textbox as a parameter to retrieve data from a database and append it to the drop down without reloading the entire page.)
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//Do stuff
}
The block off code above is in asp.net but i want to implement something similar in php.
That is not how php works. however you can make a ajax call like this with jquery:
<?php
//array, object or db result you use to fill your dropdown
$array = array('pipo', 'kees', 'klaas', 'klaas1', 'jan', 'meneerje', 'poep', 'hessel', 'kaas', 'ietsandersd', 'smit', 'cowoy', 'nog zo iets');
//if we want to search we search and only return the new found options
if(isset($_REQUEST['keyword'])){
$new_array = array();
foreach($array as $value){
if(strpos($value, $_REQUEST['keyword']) !== false){
$new_array[] = $value;
}
}
}
else{
$new_array = $array;
}
$options = '';
foreach($new_array as $key => $option){
$options .= "<option value='$key'>$option</option>";
}
$selectbox = "<select name='selectbox' id='drop_down'>$options</select>";
if(isset($_REQUEST['keyword'])){
echo $options;
}
else{
// with the \ we escape the "
echo "<html>
<head>
<title>ajax selectbox</title>
<script src=\"http://code.jquery.com/jquery-latest.min.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
$(document).ready(function () {
$('body').on('keyup', '.search', function(){
var data = $('.search').serialize();
$.post('ajax_selectbox.php', data, function (data){
$('#drop_down').html(data);
});
});
});
</script>
</head>
<body>
<input type='text' name='keyword' class='search' />
$selectbox
</body>
</html>
";
}
?>
explanation:
java script,
first we include the online jquery library, you can also download the library and include it from your own web server.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
// first we wait unit the html page is loaded
$(document).ready(function () {
//then we wait for a keyup event in the element with class="search" we use the css sector . for classes like .search
$('body').on('keyup', '.search', function(){
//when we type inside the .search textbox we serialize the element like a form would do. this takes the name and the value and puts it in a array.
var data = $('.search').serialize();
// then we post with ajax back to our php file or an other php file. its you own decision. the data variable is the serialized data form .search
$.post('ajax_selectbox.php', data, function (data){
// at least we use a calback for when the ajax event has finnest and we use the jquery html function to put the new options inside the drobbox with id="drop_down". we use the css id selector # to select the select box.
$('#drop_down').html(data);
});
});
});
</script>
note that I use jquery (and a lot of large players on the web use jquery) and if you know a little java-script the syntax can be disturbing.
In jquery we have a large set of methots we can use directly like:
$.post();
if you want to use the returned data from that function we create a calback function like:
$.post( function(param_ returned_by_parent_function){
//do stuf
});
An other way of using jquery and this is actually the idea behind it is query to a html element and then do stuff with it like this.
$('html_element_query').do_something_with_this();
of course this is just a basic basically explanation but maybe you get the idea.
You can use javascript onChange handler and send the current value to php via AJAX
https://developer.mozilla.org/en/docs/DOM/element.onchange
http://www.w3schools.com/ajax/
PHP does not know what happens on the client. If you want some events on the client to trigger actions, you have to code that yourself (usually in JavaScript).
PHP itself has no awareness of events happening on the front end. You can, however, plug the functionality (kind of) by using a mixture of Ajax and PHP. Ajax will watch for the events and PHP will process data sent to it from that Ajax.
I suggest using jQuery and checking out http://api.jquery.com/Ajax_Events/
I made a very simple PHP Event Dispatcher for myself, it is testable and has been used on my websites. If you need it, you can take a look.
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>