Form not submitting inside $.ajax success function

前端 未结 11 1709
被撕碎了的回忆
被撕碎了的回忆 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:39

    Completely due to scope

    Where you have

    alert('else working?'); // alert box is showing up if name is not duplicate                                         
    this.submit(); // but after alert, this line not executing
    

    this is referring to the ajax object, not the form. This is because it is now inside another function.

    Im adding $form = $(this); before the ajax call to declare a variable you can use inside the callback.

    Try this:

    $('#form1').submit(function( e ){
    
        e.peventDefault();
    
        var name = $('#shelf_name').val();
    
        if(name == '')
        {
            alert('Shelf name is required');
            $('#shelf_name').focus();
        }
        else
        {  
            $form = $(this);         
            $.ajax({
                type:'post',
                url:'check-duplicate-shelf-name.php',
                data:{'name':name},
                context:this,
                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                                         
                        $form.submit(); // but after alert, this line not executing
                    }
                }
            });
        }
    
    
        return false;
    });
    

    UPDATE: I may have been completely out of it yesterday. Try adding e.preventDefault(); just above the submit call. Additionally, add the e variable in the function() definition. Check the updated code above.

    Here is some documentation on preventDefault(): http://api.jquery.com/event.preventDefault/

提交回复
热议问题