I need to play an audio file when the hidden input field changes value.
This hidden input is in the <table> which is refreshed by Ajax to update the values.
What I need to do is, (for example) when the value turns to Yes the Clap.wav needs to play, otherwise, when the value turns to Noboo.wav must play.
Anyone can give me a sample code for this or an idea?
Thank you for those who are willing to help.
Here are some of my codes
This is the hidden input field code. It is located on table with the id of connExcel on platinum.php
<input type="hidden" name="indVal" id="indVal" value=" <?php echo $objWorksheet->getCellByColumnAndRow(5, 5)->getOldCalculatedValue(); ?> ">
And here are some of my Ajax codes
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById('connExcel').innerHTML=xmlHttp.responseText;
setTimeout('AutoRefresh()',100); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET","<?php if( isset( $isAdmin ) && $isAdmin == TRUE ){ echo '../../library/tosloader.php?page='. $pageID; } else { echo ../library/tosloader.php?page='. $pageID; } ?>",true);
the 'tosloader.php' just including the platinum.php to refresh the table.
in the code where you set the hidden input's value do this
$('#myHiddenID').val(myValue).trigger('change');
then just use the change event like this
$('#myHiddenID').change(function(){
var OnOff = $(this).val();
if (OnOff == "ON") { // play clap}
if (OnOff == "OFF) { //play boo}
})
Sounds like you're completely adding and removing the element from the DOM, so you'll need to watch the DOMNodeInserted event. Luckily we can bind to it. We'll assume the hidden input has a class of hiddenInput. Then we'll need to grab our source elements, aptly named <source id="yesAudio"..../> and <source id="noAudio".../> we'll use jquery's .get() method and then use the HTML5 audio api's .play(); to invoke them.
$(document).on('DOMNodeInserted', function(e){
if(e.srcElement.className == 'hiddenInput'){
if(e.srcElement.value == 'yes'){
$('#yesAudio').get().play();
}else{
$('#noAudio').get().play();
}
}
});
I think this is what you want.
jsBin demo
HTML:
<input id="inp" type="text" value="NO" />
JS:
function checkInputValue(){
var files = { "YES": "Clap.wav", "NO": "boo.wav" };
var sound = new Audio( files[ $('#inp').val() ] );
sound.play();
}
checkInputValue(); // USE WHEREVER YOU LIKE
Or you can do like:
name your files: yes.wav and no.wav
function checkInputValue( snd ){
var sound = new Audio( snd+'.wav');
sound.play();
}
var AJAXval = ("YES").toLowerCase() ; // the returned value to lowercase
checkInputValue( AJAXval );
Related
I want to take the value from text field to a variable for checking a condition
Is it possible in view? I'm using CodeIgniter.
<input type="text" id="student_gen" name="student_gen">
On form submit you can take value in javascript function like:-
var x=document.getElementbyId('student_gen').value;
If you want to do it on entering text immediately then you can call a function on onchange="myFunction()"
and in function you can take value by above method.
In action form set current_url() after submit get input in this way
$this->input->post('student_gen');
if (!$this->input->post('student_gen'))
echo 'empty field';
elseif ($this->input->post('student_gen') != 'M')
echo 'wrong value';
or You can get and check with jquery
$('#student_gen').change(function(){
if (!$(this).val() || $(this).val() != 'M')
alert('Wrong or empty value');
});
You can use jQuery:
$(document).ready(function(){
$("#student_gen").change(function(){
var x = $("#student_gen").val();
if(x=='condition'){
code..
}
});
});
or javaScript:
<script>
function myFunction() {
var x = document.getElementById("student_gen").value;
if(x=='condition'){
code..
}
}
</script>
<input type="text" id="student_gen" name="student_gen" onchange="myFunction()">
I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>
I have a small problem, I made a delete button with a PHP while loop which looks like this:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<button onclick="delconfirm()">Delete</button>
}
this echo's a few delete buttons for some content. However I need user confirmation for deleting first, this is where onclick="delconfirm()" comes in.
my confirm looks like this:
function delconfirm()
{
var r=confirm("Are you sure you want to delete this content?");
if (r==true){
// ...do nothing i guess? it needs to redirect using the PHP echo'd link...
}
else{
window.location = "edit.php";
}
}
However, whether you press cancel or ok, it'll delete it anyway. How can I fix this?
Change it to this:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<button onclick="return delconfirm();">Delete</button>
}
And then your function:
function delconfirm()
{
return confirm("Are you sure you want to delete this content?");
}
EDIT: If you want a more unobtrusive solution:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<input type="button" value="Delete" data-id="$id" />';
}
And then some javascript to bind the event:
function bindButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].type == "button") {
buttons[i].onclick = function () {
location.href='somewhere.php?id=' + this.getAttribute("data-id");
}
}
}
}
and bind it to the window.onload, as per Ian suggestion:
window.onload = bindButtons;
Note: If you were using jQuery this solution would be easier and more elegant.
Working jsFiddle
If the user presses cancel then you need to stop the event from doing what it would normally do. Try this, for example:
function delconfirm(e) {
e = e || window.event;
if (!confirm("Are you sure you want to delete this content?")) {
e.preventDefault();
// This will prevent the event from bubbling up to the <a>.
e.stopPropagation();
return false; // For the ancient/crappy browsers still out there.
}
return true;
}
You need to stop/delete the current click event. After your code is executed the event sinks to the anchor and triggers a click. With MooTools just add 'new Event().stop();'. I think jQuery has also something like this.
EDIT: Hanlet Escaño is right. You can return true (the browser will redirect to the URL in the href, or false to let the browser do nothing)
In order to prevent to the HTML link to work, you have to return false in your js function or event.preventDefault() where event is an argument which is passed to the click event function
I did thin when putting a click event on the a element and not on an element inside the a tag. But it might work.
I have been working on creating a form with a set of fields like username, passwords etc....
I want to make validation when the SUBMIT button is clicked.
I'm trying to get alert from my border color. All fields are valid my border must change into Green color If it has any errors it should change to red color.
Any one has any ideas regarding to my problem
If anyone has any suggestion??
You can use jquery plugin.... here you are. JQuery Form validation custom example
Use jQuery validation plugin: http://docs.jquery.com/Plugins/Validation
In this plugin, you have to define validation rules for the field. You can also set the error messages for given field for given validation rule.
This plugin adds classes to valid and invalid field.
You have to give the css for that class.
For example:
$(document).ready(function(){
$(".my_form").validate({
rules:{ // validation rules
email_address: {
required:true,
email: true
},
password:{
minlength: 6
},
confirm_password: {
equalTo:"#password"
}
},
messages: {
email_address: {
required: "Please enter email address",
email: "Please enter valid email address",
},
/*
likewise you can define messages for different field
for different rule.
*/
}
errorClass: "signup_error",
/*This is error class that will be applied to
invalid element. Use this class to style border.
You can give any class name.*/
});
});
Once you click on submit button, and field is invalid, the plugin adds class to the element that you have specified as errorClass, and when you enter valid value in the field, the plugin will remove this class and will add 'valid' class by default.
You can use these two classes to style valid and invalid element using simple element.
.valid {
border-color:"green"
}
.signup_error {
border-color:"red"
}
Hope this resolves your problem.
Js i the way to go. You can find some really good validators for jQuery should you google for it.
To custom build a simple validator I would go like this
<form class="validator">
<input type="text" name="my-input-1" data-validator="integer"/>
<input type="text" name="my-input-2" data-validator="email"/>
....
</form>
<script>
$("form.validator").submit(evt, function() {
var errors = 0;
$(this).find('[data-validator]').each(function(e, i) {
var value = $(this).value;
switch($(this).data('validator')) {
case 'integer':
if (!(parseFloat(value) == parseInt(value)) && !isNaN(value)) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
case 'email':
if (..... // regex validate email ...) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
}
});
if (errors > 0) {
// If you want to prevent default event execution no matter what
evt.preventDefault();
// If you want you other attached events to NOT run
evt.stopPropagation();
// signal failure
return false;
}
// All is well, go on
return true;
});
</script>
of course it's always good practice to build functions for every validator and even better to wrap the whole thing in a jQuery widget (I would suggest using jQuery Widget Factory) which would allow you to enhance it in the future and keep you flexible to changes
You can use DOJO library to validate form fields. It's easy to implement.
Given below is the tutorial to implement dojo
http://dojotoolkit.org/documentation/tutorials/1.6/validation/
and this is the working example you can see...
http://dojotoolkit.org/documentation/tutorials/1.6/validation/demo/dijitcheck.html
I made a validation library just for general javascript purposes. It is even unit tested! You can override whatever you want fairly easily as well: https://github.com/parris/iz
As far as highlighting invalid fields you can just change the style of that field or add a class. The example below just changes the background color of the input and adds a message.
Working example: http://jsfiddle.net/soparrissays/4BrNu/1/
$(function() {
var message = $("#message"),
field = $("#field");
$("#the-form").submit(function(event) {
if (iz(field.val()).alphaNumeric().not().email().valid){
message.text("Yay! AlphaNumeric and not an email address");
field.attr("style","background:green;");
} else {
message.text("OH no :(, it must be alphanumeric and not an email address");
field.attr("style","background:red;");
}
return false;
});
});
The validator is called iz. It simply lets you chain validations together and it will tell you if everything passed or if you check the "errors" object it'll give you more specifics. Beyond that you can specify your own error messages. Check the docs on github.
What is happening here is we are setting a click handler for the submit event once the page is ready. return false; at the bottom of the submit callback prevents the form from submitting. If you return true; the form will continue on. Instead of return false you could also event.preventDefault(); but I prefer the return syntax for consistency. In the real world with multiple form elements you may do something like this (psuedo code):
var passed = true;
if (check field 1 is false)
...
if (check field 2 is false)
...
if (check field n is false)
passed = false
style and add message
if passed
return true
else
return false
The if statement checks the validation rules and makes changes to the DOM accordingly. By doing it in this way you are able to give a complete list of all passed and failed fields with a full description of what is incorrect.
I have used this plugin in the past, makes implementation very easy and has good documentation and examples.
My advice use jQuery
to try first create multiple inputs and give them a class
html:
<input type="text" class="validate" value="asdf" />
<input type="text" class="validate" value="1234" />
<input type="text" class="validate" value="asd123" />
<input type="text" class="validate" value="£#$&" />
<input type="text" class="validate" value=" " />
then use the code below to see how it works
jQuery:
// Validate Function
function validate(element) {
var obj = $(element);
if (obj.val().trim() != "") {
// Not empty
if (!/^[a-zA-Z0-9_ ]{1,10}$/.test(obj.val())) {
// Invalid
obj.css('border-color', '#FAC3C3');
if (!obj.next().hasClass('error'))
{ obj.after('<span class="error">Please use letters or numbers only and not more than 10 characters!</span>'); }
else
{ obj.next().text('Please use letters or numbers only and not more than 10 characters!'); }
} else {
// Valid
obj.css('border-color', 'lightgreen');
if (obj.next().hasClass('error'))
{ obj.next().remove(); }
}
} else {
// Empty
obj.css('border-color', '#FAC3C3');
if (obj.next().hasClass('error'))
{ obj.next().text('This field cannot be empty!'); }
else
{ obj.after('<span class="error error-keyup-1">This field cannot be empty!</span>'); }
}
}
$(document).ready(function() {
// Each
$('.validate').each(function() {
// Validate
validate(this);
// Key up
$(this).keyup(function() {
// Validate
validate(this);
});
});
});
jsfiddle : http://jsfiddle.net/BerkerYuceer/nh2Ja/
A server side validation example of your need. You may try it out.
<?php
error_reporting(0);
$green = "border: 3px solid green";
$red="border: 3px solid red";
$nothing="";
$color = array ("text1"=>$nothing , "text2"=>$nothing) ;
if ( $_POST['submit'] ) {
if($_POST['text1']) {
$color['text1'] = $green;
}
else $color['text1'] = $red;
if($_POST['text2'] ) {
$color['text2'] = $green;
}
else $color['text2'] = $red;
}
?>
<form method="post">
<input type="text" name="text1" style="<?php echo $color ['text1']?>" value="<?php echo $_POST['text1']?>">
<input type="text" name="text2" style="<?php echo $color ['text2']?>" value="<?php echo $_POST['text2']?>">
<input type="submit" name="submit">
</form>
Note
Always sanitize user input.
error_reporting off is not a good practice at all. I did it as this is not a code of production environment.
Check before trying to access in the post array using isset or something similar function like this.
Always check if a variable exist before using.
$("#btn").click(function(){
// Check all of them
if( $.trim($("#file").val()) == ""){
$("#file").css("border","1px solid #ff5555");
}else{
$("#file").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimBaslik").val()) == ""){
$("#showboxResimBaslik").css("border","1px solid #ff5555");
}else{
$("#showboxResimBaslik").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimEtiket").val()) == ""){
$("#showboxResimEtiket").css("border","1px solid #ff5555");
}else{
if($.trim($("#showboxResimSehir").val()) == ""){
$("#showboxResimSehir").css("border","1px solid #ff5555");
}else{
$("#showboxResimSehir").css("border","1px solid #cccccc");
$("#resimYukleForm").removeAttr("onSubmit");
$('#resimYukleForm').bind('submit', form_submit);
}
}
}
}
});
probably the easiest way is to use this javascript:
http://livevalidation.com/examples#exampleComposite
I think it suits your description the best.
check below link, here i have only checked for empty fields and if the fields are empty then changed input fields id which will change input field border color.
http://jsfiddle.net/techprasad/jBG7L/2/
I have used
$("#myb").click(function(){
that is on button click event but you can use submit event.
Here is what I would say is short precise and concise way to do this in jQuery.
HTML:
<form id="myform" name="form" action="http://www.google.com">
<div class="line"><label>Your Username</label><input class="req" type="text" /></div>
<div class="line"><label>Your Password</label><input class="req" type="password" /></div>
<div class="line"><label>Your Website</label><input class="req" type="text" /></div>
<div class="line"><label>Your Message</label><textarea class="req"></textarea></div>
<div class="line"><input type="submit" id="sub"></submit>
</form>
CSS:
.line{padding-top:10px;}
.inline input{padding-left: 20px;}
label{float:left;width:120px;}
jQuery:
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid green");
$(".req").each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0) {
$(this).css("border","1px solid red");
valid = false;
}
});
return valid;
}
$("#sub").click(function() {
$('#myform').submit(validateform);
$('#myform').submit();
});
});
LIVE DEMO
Well hi, you can use html5 "required" and "pattern" in your form's fields.
You'll get red border if it's wrong and green if it's right.
You can even style the :valid and :invalid entry fields if the colors aren't which you wanted.
I've never tested it but why not, it's better than nothing ;)
html5 solution
Firs Learn javascript, if you have some basic knowledge of js and need to know the logic, go on read..
First you need an event handler to run a function on form submit
Easiest way is (though there are better ways)
<form action="som.php" onsubmit="functionName()">
form here
</form>
This will trigger the function called functionname.
In function name function access the input fields and validate using regular expressions
function functionName()
{
//verification code
if(verified)
{
//code to change border to green
}
}
You need to get the input fields and validate them. If you don't know how to do that, get a few Javascript books
If you need to validate as soon as value is typed use the on onchange event on input fields
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the
$(document).ready(function(){
But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js
$(document).ready(function(){
$('#AddCaller').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var Firstname = $('#Firstname').val();
...OTHER FORM FIELDS HERE
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut. */
if(Firstname.length == 0){
var error = true;
$('#Firstname_error').fadeIn(500);
}else{
$('#Firstname_error').fadeOut(500);
}
if(Lastname.length == 0){
var error = true;
$('#Lastname_error').fadeIn(500);
}else{
$('#Lastname_error').fadeOut(500);
}
...MORE CONDITIONAL STATEMENTS HERE
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'added'){
//$('#cf_submit_p').remove();
//and show the success div with fadeIn
$('#Add_success').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
document.getElementById('Firstname').value = "";
document.getElementById('Lastname').value = "";
document.getElementById('PhoneNumber').value = "";
document.getElementById('DefaultETA').value = "";
document.getElementById('Apparatus').value = "";
document.getElementById('DefaultLocation').value = "";
setTimeout(" $('#Add_success').fadeOut(500);",5000);
}else if(result == 'alreadythere'){
//checks database to see if the user is already there
$('#Alreadythere').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
}
else{
//show the failed div
$('#Add_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.
Thanks for the help!
EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.
EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.
<form action='addcallers.php' method='post' id='AddCaller_form'>
<h2>Add Callers</h2>
<p>
First Name:
<div id='Firstname_error' class='error'> Please Enter a First Name</div>
<div><input type='text' name='Firstname' id='Firstname'></div>
</p>
<p>
Last Name:
<div id='Lastname_error' class='error'> Please Enter a Last Name</div>
<div><input type='text' name='Lastname' id='Lastname'></div>
</p>
...MORE FORM FIELDS HERE
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly >
</div>
</p>
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='AddCaller' value='Send The Message'>
</p>
</form>
</div>
EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.
EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it
EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?
most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:
document.getElementById('DefaultLocation').value = "";
And never changing it's value back to something (or are you?)
so you have to do one of the following:
don't reset it
set it's value with something after posing the form
don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!
also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..
anyway, here are sometips for you:
1- close the input tags correctly (add / to the end of it):
<input type='text' name='Firstname' id='Firstname' />
2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
</p> <---- missing this one
<p id='cf_submit_p'>
3- you are redeclaring the error variable all the time, you don't need to do that:
if(Firstname.length == 0){
var error = true;
....
just use error = true; without var this applies on all places you are changing its value only use var on initialization:
var error = false;
4- instead of this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
use:
$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });
5- if you are using DefaultLocation as a hidden field then instead of this:
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly />
</div>
use:
<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />
Try to change from using the click event handler to the form's submit event handler
Change this : $('#AddCaller').click
To this : $('#AddCaller_form').submit
Do not remove the attribute of disabled, set it to false.
This line
$('#AddCaller').removeAttr('disabled').attr(...
should be
$('#AddCaller').attr('disabled', false).attr(...
I assume that by removing and adding attributes, the element is removed and replaced by the new one, but the handler is not re-attached. Try using $('#AddCaller').live('click', function(){ //code }) instead of .click()
This function send queries to php and can return results from the php file using ajax.
I have left comments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2
function ajaxFunction(){
var ajaxRequest;
//Browser compatible. keep it as it is
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//Browser compatible end
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//#2 opional: create functions to return data from your php file
$('#resultArea').html(ajaxRequest.responseText);
}
}
//#1 Set the form method, filename & query here here
ajaxRequest.open("GET", "serverTime.php?query=something", true);
ajaxRequest.send(null);
}
example:
<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
quick jquery plugin for that since you might use this in almost every ajax form on your site:
it will disable all fields that could trigger a submit event and also add a class on the form tag so that you can apply some styling, or showing a load message when the form is submitted:
jQuery.extend(jQuery.fn, {
formToggle: function (enable){
return this.each(function(){
jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
.find(':input').attr('disabled', !enable);
},
enable: function(){ return this.formToggle(true); },
disable: function(){ return this.formToggle(false); }
}
then on your jq ajax code:
[...]
var $form = $(your_form).submit(function(){
$.ajax({
type: 'post',
url: "/whatever/",
data: $form.serialize(),
success: function (){ alert ('yay');},
complete: function(){ $form.enable();},
error: function(){ alert('insert coin')}
}
$form.disable();
return false;
});
It should be enough to properly block the submits while the forms is sending/receiving data.
If you are really paranoid you can add a check so that it cannot be sent twice between the moment the user triggers the submit and the fields get disabled with : if ($form.is('.disabled')) return false; as first line of the submit handler, but it shouldn t be necessary really
Set some breakpoints in Firebug and watch if it goes somewhere.
Button can lose its click handler after submit and applying effects. You probably need to assign click handler again after submit and stuff.
Not 100% on this but try setting the code as a separate function then rebinding the click event at the end.
Example:
function addCaller(e) {
// your unchanged code
$('#AddCaller').click(addCaller(e));
}
$(document).ready(function(){
// added an unbind just in case
$('#AddCaller').unbind('click').click(addCaller(e));
});
Try to change this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that:
$('#AddCaller').attr({'value' : 'Adding...' });
This should make it work.