最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Jquery form only working the first time you submit it, and not the second - Stack Overflow

programmeradmin3浏览0评论

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 .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 / 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?

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./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./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?

Share Improve this question edited Dec 16, 2010 at 3:52 Bill asked Dec 14, 2010 at 14:06 BillBill 5,67817 gold badges66 silver badges97 bronze badges 20
  • From quick look, this should work fine. Add alerts in key lines and see where it stop or better yet debug it with Firebug or something equivalent, and let us know the results. – Shadow Wizzard Commented Dec 14, 2010 at 14:13
  • Yes - in particular, I'd use an "alert()" or "console.log()" to make sure that the "click" handler is being invoked on the second pass through. – Pointy Commented Dec 14, 2010 at 14:18
  • The click event isn't being called the second time. You can click the button all you want, but it doesn't do anything – Bill Commented Dec 14, 2010 at 14:19
  • Muy interesting! Could you post the html as well? – Spiny Norman Commented Dec 14, 2010 at 14:26
  • @Spiny I added the HTML for the form above – Bill Commented Dec 14, 2010 at 14:33
 |  Show 15 more ments

9 Answers 9

Reset to default 4 +50

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" />

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 ments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2

 function ajaxFunction(){
        var ajaxRequest;  


        //Browser patible. 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 patible 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');},
    plete: 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.

发布评论

评论列表(0)

  1. 暂无评论