Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Dana Griffin
Dana Griffin
5,870 Points

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

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");
    }
});