简体   繁体   中英

AJAX-enabled form will only submit once using AJAX, then defaults to HTTP request

AJAX-enabled form will only submit once using AJAX, then defaults to using a standard HTTP request. Code is below:

    $('#urlContainer form').submit(function(){

        var p = {};
        p['url'] = $('input#url').val();

        if($('#urlContainer #results').length != 0){
            $('#urlContainer #results').fadeOut(1000, function() {
                $('#urlContainer').load(location.href+' #urlContainer>*',p,function(){
                    $('#urlContainer #results').hide();
                    $('#urlContainer #results').fadeIn(1000);

                });
            });
        } else {
            $('#urlContainer').load(location.href+' #urlContainer>*',p,function(){
                $('#urlContainer #results').hide();
                $('#urlContainer #results').fadeIn(1000);

            });
    }
    return false;
});

Any ideas?

Thanks in advance.

$('#urlContainer').load(...)

This code replaces all the content within #urlContainer . All the elements are replaced, which means that all event handlers bound to them will also be replaced. You should use delegate() to run code for events on elements that may not exist yet:

$('#urlContainer').delegate('form', 'submit', function(){
    // the code from your submit handler
});

Alternatively, you could rewrite your code to avoid obliterating the form element, so the handler on it would persist.

The jQuery load function replaces the contents of the matched elements with the result of the AJAX call. When that happens, the form that you are binding to is removed (or replaced), so the original event handler does not trigger.

If you use .live('submit' ...) instead of .submit , it should resolve your issue:

$('#urlContainer form').live('submit', function(){
    ...
});

The live method attaches to current and future elements that match the selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM