Ashley Brown Ashley Brown - 3 months ago 17
jQuery Question

Why won't this form submit with AJAX?

I'm trying to submit a form to Campaign Monitor. They offer this code example to POST via Ajax.

This is my code for my multi-step modal.

var next_step = false;
var final_step = false;

$('.next').on('click', function(e){
e.preventDefault();

if (next_step) {
$('#step-1').slideUp(function(){
$('#step-2').slideDown();
$('.next').html('Submit');// Change button text to submit
final_step = true;
});
}
next_step = true;

if (final_step) {
$('#myform').submit(function (e){
alert('submit started'); //This never fires unless I remove the preventDefault();
e.preventDefault();//But if I remove this, the page will refresh
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert('error');
} else {
alert('success');
}
})
});
}
});


On the last step of the form, I check whether
final_step
is true, if so, go ahead and submit the form via ajax.

The problem is that it just doesn't do anything? But if I remove the
e.preventDefault();
from the
$('#myform')
it will post the form as normal and re-direct you to the form URL.

How can I fix this?

Answer

What you are doing currently is wiring up an onsubmit handler. Not invoking submit.

 $('#myform').submit(function (e){ }); 

...is the same thing as...

<form action="#" method="post" onsubmit="return someFunction()">

... which is the same as ...

$('#myForm').on('submit', function(e){});

You are never submitting the form.

What you are looking for is to use Ajax to post the data to the server and not submit the form.

You can do that like this:

$.ajax({
    type: "POST",
    url: "SomeUrl.aspx",
    data: dataString,
    success: function() {
      //display message back to user here
    }
  });

dataString would be replaced with the values you posting.