Form not submitting inside $.ajax success function

2020-04-07 05:14发布

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's Happening

  • If no name is entered, alert box is showing up stating name is required --> No problem here
  • If duplicate name is found, alert box is showing up stating name already exists and form does not submit --> No problem here
  • If duplicate name is not found, alert box is showing up (to prove the else part of the condition is working), but the form does not submit. I want the form to go ahead and submit itself in this else part

jQuery Code

$('#form1').submit(function(){

    var name = $('#shelf_name').val();

    if(name == '')
    {
        alert('Shelf name is required');
        $('#shelf_name').focus();
    }
    else
    {                   
        $.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                                         
                    this.submit(); // but after alert, this line not executing
                }
            }
        });
    }


    return false;

});

HTML Form Tag

<form action="add-shelf-post.php" method="post" id="form1">

check-duplicate-shelf-name.php Page

<?php

include 'confignew.php';

$name = $_POST['name'];

// peforming database operations
.
.
.

// and then

if($db->num_rows($q) == 0)
{
    echo 'go';
}
else
{
    echo 'stop';
}

I'm missing something very obvious. Hopefully someone here can point that out.

After checking with Firebug in Firefox, I indeed got an error. It didn't show up when I was testing with Chrome. Here is the screenshot.

Firebug Error

11条回答
干净又极端
2楼-- · 2020-04-07 05:20

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/

查看更多
可以哭但决不认输i
3楼-- · 2020-04-07 05:21

You can benefit from the callbacks in this case. Just separate the code like below:

function with the callback that will return an object {status: 'true or false', message: 'Some text'}

function validity(callback){

    var name = $('#shelf_name').val();

    if(name == '')
    {
        return callback({status: false, message: 'Shelf name is required'});
    }
    else
    {                   
        $.ajax({
            type:'post',
            url:'check-duplicate-shelf-name.php',
            data:{'name':name},
            context:this,
            success:function(data)
            {
                if(data == 'stop')
                {
                     return callback({status: false, message: 'Shelf name already exists'});                    

                }
                else
                {   
                    return callback({status: true, message: 'else working?'});
                }
            }
        });
    }

     //just for safety :))
    return callback({status: false, message: 'something went wrong completely'});
});

This returns the result from the AJAX call. It will wait for AJAX to complete and return the corresponding branch result of if...

.. and you can now use it as this:

$('#form1').submit(function(){
    validity(function(result){
       if (result.status) { //status is true
           return true;
       } 
       else
       {
           alert(result.message);
           $('#shelf_name').focus(); 
           return false;      
       }
    });
});

... or just combine them like :

$('#form1').submit(function(){

        // definition
        function validity(callback){

            var name = $('#shelf_name').val();

            if(name == '')
            {
                return callback({status: false, message: 'Shelf name is required'});
            }
            else
            {                   
                $.ajax({
                    type:'post',
                    url:'check-duplicate-shelf-name.php',
                    data:{'name':name},
                    context:this,
                    success:function(data)
                    {
                        if(data == 'stop')
                        {
                             return callback({status: false, message: 'Shelf name already exists'});                    

                        }
                        else
                        {   
                            return callback({status: true, message: 'else working?'});
                        }
                    }
                });
            }

             //just for safety :))
            return callback({status: false, message: 'something went wrong completely'});
        });

        //usage
        validity(function(result){
            if (result.status) { //status is true
                return true;
            } 
            else
            {
                alert(result.message);
                $('#shelf_name').focus(); 
                return false;      
               }
            });
        });

Hope this helps

查看更多
爷、活的狠高调
4楼-- · 2020-04-07 05:21

We had the same problem and think we sorted out.

The thing is that the .submit() action doesn't work inside the "thread" $.ajax neither $.post. For that you have to add the async:false instruction inside the $.ajax block and submit the form when the $.ajax execution finishes.

Not tested but this is the working idea:

html:

<input type='submit' onClick='javascript:MyCheck(); return false;'>

javacript:

function Mycheck() {

   var result = "";
   $.ajax {
       async:false,
       url: you_url_here,
       timeout: 15000,
       success: function(data) {
            result="success";
       },
       error: function(request, status, err) {
            result="error";
       }
   };

   // Here, if success -> SUBMIT FORM or whatever
   // Only get here if "ASYNC" = FALSE!!!
   if (result == "success") {
       $("form").submit(); // this submits the form
       return;
   } else {
       alert('error');
       // the form will not be post
   }
}
查看更多
三岁会撩人
5楼-- · 2020-04-07 05:23
$('#form1').submit(function(){

    var name = $('#shelf_name').val();

    if(name == '')
    {
        alert('Shelf name is required');
        $('#shelf_name').focus();
    }
    else
    {                   
        var istrue = false;        
        $.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');
                    istrue = false;
                }
                else
                {   
                    alert('else working?') // alert box is showing up                           
                    istrue = true;
                }
            }
        });
        return istrue;
    }
});

some thing like this :) cant test

查看更多
爷的心禁止访问
6楼-- · 2020-04-07 05:34

I've tested your code and it works in Chrome, IE 8 and Mozilla Firefox. Check whether in your whole page there is an element which contains in it's name attribute value the word submit. If there is rename it. For example an input tag like this: <input type="submit" name="submit" value="Submit Form"/> will cause the error appeared in your Mozilla Firebug.

Furthermore below you can find an alternative solution.

The following solution has been successfully tested in Chrome, IE 8 and Mozilla Firefox.

Alternative Solution

Retrieve the post URL and the data that you want to post and perform a post in the success callback.

The following implementation has been successfully tested in Chrome, IE 8 and Mozilla Firefox. In the success callback, the data to be posted is retrieved and posted to the URL and the result is put to a div with id result. You can modify it in order to fit your needs.

$(document).ready(function() {
    $('#form1').submit(function(){
        var name = $('#shelf_name').val();
        if(name == '')
        {
            alert('Shelf name is required');
            $('#shelf_name').focus();
        }
        else
        {
            $.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');
                    }
                    else
                    {   
                        alert('else working?'); 
                        //this.submit();
                        //$(this).submit();

                        // get the post url and the data to be posted
                        var $form = $(this);
                            shelfNameVal = $form.find( 'input[id="shelf_name"]' ).val(),
                            url = $form.attr( 'action' );

                            // Send the form data and put the results in the result div
                            $.post(url, { shelf_name: shelfNameVal },
                                function(data) {
                                    $( "#result" ).empty().append(data);
                                }
                            );
                    }
                }
            });
        }
    return false;
    });
});

I hope this helps.

查看更多
Luminary・发光体
7楼-- · 2020-04-07 05:34

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.

查看更多
登录 后发表回答