0

I'm stuck with returning.

I need that if response is "ok", my form would be submitted else document wouldn't reload.

I've tried like that:

$(window).load(function(){
$('.check-connection').click(function(){
    u = {};
    u["host"] = $('[name="host"]').val();
    u["db_user"] = $('[name="db_user"]').val();
    u["db_pass"] = $('[name="db_pass"]').val();
    u["db_name"] = $('[name="db_name"]').val();
    $.post('check-connection.php',{secure:true,data:u}).done(function(r){
        if(r == "ok"){
            /*
                here problems even returns ok
                alert(r); - gives answer ok if trying to check..
            */
            return true;
        } else {
            alert(r);
            return false;
        }
    });
    return false;
});

});

Any ideas? offers?

JDSolutions
  • 115
  • 6
  • 1
    please read this: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – phylax Apr 11 '14 at 14:11
  • 1
    You should really use the proper $.post syntax for handling return values - https://api.jquery.com/jQuery.post/ – Jay Blanchard Apr 11 '14 at 14:12
  • 1
    @JayBlanchard ?? the code looks OK (other than the `return` statements); it's using the Deferred mechanism instead of the 3rd parameter callback. – Pointy Apr 11 '14 at 14:13
  • @Pointy I would have handled it in the .done(), just a preference. – Jay Blanchard Apr 11 '14 at 14:15
  • 1
    The `$.post()` operation is **asynchronous**. You can't return values. – Pointy Apr 11 '14 at 14:15
  • Seems I'll need to think how to do this in other way.. – JDSolutions Apr 11 '14 at 14:19
  • your else statement is always going to be triggered unless the data returned by the post is actually the text `ok`, are you trying to test against the response code, like `200 OK`, or is your php script actually putting out `ok`? – Patrick Evans Apr 11 '14 at 14:21
  • I sincerely hope you are not exposing your DB information on the client. HUGE security issue. – xCNPx Apr 11 '14 at 14:57
  • PHP checks and response only OK or Error. Nothing else. It's just checking if user can connect database with entered details. – JDSolutions Apr 12 '14 at 17:49

2 Answers2

0

Probably you might want to remove the last return false; because it is returning before the ajax completes.

Let it return when the .done() handler is executed.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

You can not return a boolean from within the ajax done function and expect it to be passed back to the click handler. The ajax is asynchronous and so the click handler will complete execution before the ajax response is received.

The logic should be: call the ajax on a button click (not form submit), then submit the form from within the ajax success handler, else don't do anything.

MrCode
  • 63,975
  • 10
  • 90
  • 112