Alan Wareham
Alan Wareham

Reputation: 31

.submit() not working correctly, unbind() helps but comes with a side affect

Will keep it short and sweet:

Any help in being able to submit the form straight away would help me a great deal :)

The code as it is works, apart from when username is available it does not submit, the line that is commented out allows it to submit but as mentioned before only after second click of submit button.

$(document).ready(function()
{

$(".f_create").submit(function()
{ 

    var username = $(".userID").val();

    $.ajax({  
      type: "POST",
      url: "id_check.php",  
      data: "userID="+ username,  
      success: function(response){

        if(response=="NO"){
            $('.l_userID').append('<label class="format" style="color:blue">Nope</label>');   
        }
        else if(response=="YES"){   
            // $(".f_create").unbind();  ..... submits the form but only on second click of submit button
            $(".f_create").submit();

        }

      }

    });

    return false; 

});

});

Upvotes: 2

Views: 1294

Answers (1)

Rob W
Rob W

Reputation: 349062

You can define an optional parameter at your submit function. When you manually trigger the submit method again, pass a parameter, true to submit the real form.

$(".f_create").submit(function(e, explicitSubmit){ 
    if (explicitsubmit) {
         //If the flag is defined, cancel function.
         return; //<-- Return. Form will be "normally" submitted.
    } else {
        // By default, prevent a submission
        e.preventDefault();
    }
    var username = $(".userID").val();

    $.ajax({  
      type: "POST",
      url: "id_check.php",  
      data: "userID="+ username,  
      success: function(response) {
        if (response == "NO") {
            $('.l_userID').append('<label class="format" style="color:blue">Nope</label>');   
        }
        else if (response == "YES") {
            $(".f_create").trigger("submit", [/* explicitSubmit */true]);

        }
      }
    });
});

Upvotes: 3

Related Questions