0

I would like to know how to handle a problem I have. I have a form that on submit checks if an entry is already present in the database (double names are forbidden). The call itself works fine. Here is the function that utilizes $.ajax:

function checkActionName(action_name) {
    $.ajax({
        type: "POST",
        url: "ajax/action_checks.php",
        data: { 
            action_task: "checkActionName", 
            action_name: action_name
        },
        dataType: "text",
        timeout: 6000,
        success: function (response) {
            if (response == 0){
                return 0;
            } 
            else if (response == 1) {
                return 1;
            }
            else {
                return 2;
            }
        },
        error: function(){
            return 2;
        }
    });
}

Later in my code I call this function like this:

$('#button').click(function(){
   var action_name = "test";
   var check = checkActionName(action_name);
   alert(check);
});

The problem is that since the AJAX call runs asynchronous, check will be undefined. Since async: false is deprecated, what is the best/most compliant way (as of August 2016) to handle this situation so that alert(check) will give me the return value of checkActionName?

Is it $.when? I kinda struggled with this, most answers for problems like this suggest async:false and I dont want to use it.

Broco
  • 217
  • 2
  • 18
  • You could return the *$.ajax()* and use *$.when()* to handle the result. Keep in mind that if you write your code in a way that is blocking, that means that your app will wait until the code finish the task, as javascript is not multithread. – Mario Santini Aug 24 '16 at 15:36
  • @MarioAlexandroSantini Yes, that is the plan, since the function is part of a submit process and during that the inputs are being compared with entries in the database to prevent same names. So if the check fails the modal stays open and puts out error messages under the inputs. So $.when is the way to go? I just wanted to know about the best practice. – Broco Aug 24 '16 at 15:41

0 Answers0