开发者

JQuery AJAX submit button sometimes doesn't work

Greetings all,

I'm using a link as an JQuery AJAX submit button, and sometimes it fires when clicked and sometimes it doesn't. The failure to fire is intermittent. It seems like it happens after the AJAX form is submitted but returns with errors which I display.

Then when I click the submit button/link again sometimes nothing happens, and sometimes it works fine. No javascript errors show on the console. Here is what my code looks like. I would appreciate your thoughts. Do I need to be using .live()? And if so, why? I'm thinking maybe I don't understand how the binding works fully.

Thanks, -Northk

// make the comment form submit link behave as if it's a submit button.
// this code is inside $(document).ready.  Corresponding HTML looks like:
//      <div class="box round-box d开发者_JAVA百科arker comment-message-box">
//          <p class="comment-message"></p>
//      </div>    
//
// <a href="#" id="comment-button" class="action-button"><small>Submit</small></a>      
//
$(function() {
    $('#comment-button').click(function(e) {
        e.preventDefault(); // prevent the browser from "jumping" on the page when it comes back from AJAX. 
        $('.comment-message-box').hide(); // clear any leftover errors that may be showing on the form    
            $('#comment_form').submit(); 
    });
});

Sorry, here is the AJAX code. I was trying to keep my question short but probably didn't give enough code-context:

$(function() {
    $('#comment_form').ajaxForm({
        url: 'http://www.mywebsite.com',
        success: function(data) {
            if (data.match(/<title>Error<\/title>/)) {
                //grab the error message
                var error = $(data).find('ul li:first').text();

                // if they didn't enter any comment, this is the error we'll get back from the server
                if (error == 'The comment field is required')
                {
                    $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Please enter a comment.</p>');
                } 
                // else some other kind of error occurred
                else  
                {
                    $('.comment-message').replaceWith('<p class="comment-message mtm mbm">I&rsquo;m sorry! for some reason the comment form isn&rsquo;t working at this time. Please <a href="/contact">contact me</a> for help.</p>');                      
                }
            }
            else {
                 // else no error, fix up a success message
                $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Thanks for your comment!</p>');
                }
                // display the return message box
                $('.comment-message-box').fadeIn(1000); 
            },
        dataType: 'html'
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜