JavaScript AJAX Basics (retiring) jQuery and AJAX Posting Data with jQuery

Dana Griffin
Dana Griffin
5,870 Points

Submitting a form using an anchor tag

I am having trouble submitting a form using ajax. The button is an anchor tag that submits the form if certain requirements are met. Any help would be great!

HTML:

<form id="form" method="post" action="/signUp">

    .........

  <a href="#" id="signUpBig" class="button button-block button-rounded button-large">Sign Up</a>
</form>

JS:

  $(document).on("click","#signUpBig",function(){
    if (canSubmit()) {
        $('form').submit(function(evt){
            evt.preventDefault();
            var url = $('form').attr("action");
            var formData = $('form').serialize();
            $.post(url, formData, function(response){
                console.log(response);
            });//end post
        });//end submit
    } else {
        console.log("the forms info is not valid");
    }
});

2 Answers

Timothy coxon
Timothy coxon
18,404 Points

I think this should probably work for you... You seem to have got a little confused over handling and triggering the submit event.. http://api.jquery.com/submit/

  $("#form").submit(function(){ //Handle the sumbit here.           
            var url = $("#form").attr("action");
            var formData = $("#form").serialize();
            console.log(url);
            $.post(url, formData, function(response){
                console.log(response);
            });//end post
  });//end submit

  $(document).on("click","#signUpBig",function(evt){
    evt.preventDefault();    
    if (canSubmit()) {
        $("#form").submit(); //Trigger the Submit Here
    } else {
        console.log("the forms info is not valid");
    }
});
Dana Griffin
Dana Griffin
5,870 Points

Turns out that I forgot the name attribute on my inputs.