Form not submitting inside $.ajax success function

前端 未结 11 1576
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 20:34

I\'m validating for duplicate names by using jquery+Ajax. Everything is working fine except that the form is not submitting once everything returns true

What

11条回答
  •  鱼传尺愫
    2021-01-18 21:15

    The reason the form is not submitting is that you are returning false from the submit event handler, which causes the default action (submission) to not occur. Even if you call the submit() method, you're still within the submit event handler, which has returned false.

    You may want to consider either changing the server-side logic which handles your form submission to also check for duplicates, or attaching the duplicate check ajax post to the blur event of the text box, or a submit button as suggested by @rajesh kakawat (except attaching with jQuery rather than an HTML attribute). Example:

    $('#form1').submit(function(){
    
        var name = $('#shelf_name').val();
    
        if(name == '')
        {
            alert('Shelf name is required');
            $('#shelf_name').focus();
            return false;
        }
    });
    
    $('#shelf_name').on('blur', function () {
        var $this = $(this),
            name = $this.val();
        if(name == '')
        {
            alert('Shelf name is required');
            $this.focus();
            return false;
        }
    
            $.ajax({
                type:'post',
                url:'check-duplicate-shelf-name.php',
                data:{'name':name},
                success:function(data)
                {
                    if(data == 'stop')
                    {
                        alert('Shelf name already exists'); // working if duplicate name is found
                    }
                    else
                    {   
                        alert('else working?'); // alert box is showing up if name is not duplicate                                         
                        $('#form1').submit(); // this should work now
                    }
                }
            });
    });
    

    I'm not sure why the this.submit(); line was working previously, as I don't know enough about your application, script version, etc.. You may want to consider using jsfiddle to post an example.

提交回复
热议问题