Bill
Bill

Reputation: 5688

Jquery form only working the first time you submit it, and not the second

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?

Upvotes: 6

Views: 7926

Answers (9)

Stuart Burrows
Stuart Burrows

Reputation: 10814

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));
});

Upvotes: 0

ifaour
ifaour

Reputation: 38135

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:

  1. don't reset it
  2. set it's value with something after posing the form
  3. 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" />

Upvotes: 4

JessyNinja
JessyNinja

Reputation: 153

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.

Upvotes: 0

mpenet
mpenet

Reputation: 367

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

Upvotes: 0

Zebra
Zebra

Reputation: 4006

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()' />

Upvotes: 0

s3v3n
s3v3n

Reputation: 8456

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()

Upvotes: 0

Krishna Chytanya
Krishna Chytanya

Reputation: 1438

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

Upvotes: 2

epascarello
epascarello

Reputation: 207557

Do not remove the attribute of disabled, set it to false.

This line

$('#AddCaller').removeAttr('disabled').attr(...

should be

$('#AddCaller').attr('disabled', false).attr(...

Upvotes: 1

Jacek Francuz
Jacek Francuz

Reputation: 2498

Try to change this: $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' }); into that: $('#AddCaller').attr({'value' : 'Adding...' });

This should make it work.

Upvotes: -2

Related Questions