-4

I have a basic AJAX request like so:

    $.ajax({
        url: 'check_password.php',
        type: 'post',
        data: 'password='+password,
        dataType: 'json',
        success: function(json) {
            if (json['success']) {
               //Continue with default action
            }else{
                //Password is invalid, stop the script and return an error
                preventDefault();
                $(".error").show();
            }
        }
Peter Stuart
  • 2,362
  • 7
  • 42
  • 73
  • 2
    and your question is....? – Colleen Feb 22 '13 at 22:07
  • I believe the question is "How do I get the response from an AJAX request before submitting a form" – renab Feb 22 '13 at 22:08
  • 1
    You can't without using synchronous ajax which is usually a bad idea. – Kevin B Feb 22 '13 at 22:09
  • Sorry for not being clear in my question, I ws in a hurry. I wanted the form to NOT submit if the json['success'] object was == false. Sorry for the lack of information guys :) @KevinB answer will do the trick :) – Peter Stuart Feb 23 '13 at 03:02

1 Answers1

2

I'd suggest instead preventing the default completely, then submitting the form (if it is a form) by using .submit() on the form node, thus bypassing the jQuery event handler.

$("#myform").on("submit",function(event){
    event.preventDefault();
    var form = this;
    $.ajax({
        url: theurl,
        type: "POST",
        data: thedata
        dataType: "json"
    }).done(function(json){
        if (json.success) {
            form.submit();
        }
        else {
            $("#error").show();
        }
    });    
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Sorry it's late, but thanks for poitning me in the right direction, and sorry for the crappy written question, I was in a hurry when posting it! Thanks again! – Peter Stuart Feb 28 '13 at 01:16
  • @PeterStuart No problem, glad you could get it to work. – Kevin B Feb 28 '13 at 02:56