1

Instead of all sorry for the misleading title, I'll try to explain better. My customer fill a form with personal information, this information are validate from an ajax request that calls a php function. This php function return SUCCESS if the validation it's successfull, instead return the exception. Now when the user click on the next button the javascript code call this function:

if(!FrontendBook.validateCustomerForm())
{   
     return; //FAIL
} else
{
    //do stuff
}

the validateCustomerForm function contain this:

var postUrl = GlobalVariables.baseUrl + 'backend_api/ajax_save_customer';
var postData = { 'customer': JSON.stringify(GlobalVariables.customerData) };

$.post(postUrl, postData, function(response)
{    
      if(response.status == "SUCCESS")
      {
            return true;
      }
      else
      {
            return false;
      }

}, 'json');

Now in the browser console I see correctly the reponse content, and if I put an alert inside response.status == "SUCCESS" the alert is displayed correctly.
Initially I don't understood why in the if(!FrontendBook.validateCustomerForm()) the code enter in the return statement, so in the fail validation. But I ran this test:

  1. Print the result of FrontendBook.validateCustomerForm in console.log()
  2. Check in which statement the condition was

In console.log I get undefined and of course the condition statement fall into the return; //FAIL.
Maybe this is a problem of time? Someone could explain why the function return undefined when I return true or false in the specific contest?

scniro
  • 16,844
  • 8
  • 62
  • 106
Dillinger
  • 1,823
  • 4
  • 33
  • 78
  • first, `return` inside the callback does not return to outer function. Second, even if it did, ajax is asynchronous so you can't do what you are doing expecting your function to synchronously return boolean – charlietfl Jan 02 '16 at 15:42
  • so for fix this I should insert the validation code inside the checking condition, right? – Dillinger Jan 02 '16 at 15:43
  • yes, or return promise from the function – charlietfl Jan 02 '16 at 15:44

1 Answers1

1

You seem to be misunderstanding promises and the asynchronous nature of this function call. Observe the following way we can accomplish this...

// declaration
function validateCustomerForm() {

    var postUrl = GlobalVariables.baseUrl + 'backend_api/ajax_save_customer';
    var postData = { 'customer': JSON.stringify(GlobalVariables.customerData) };

    return $.post(postUrl, postData); // return promise object
}

// usage
validateCustomerForm().done(function(response) { // resolve promise

    if(response.status == "SUCCESS")
    /*...*/

});

Check out the jQuery deferred api for more information - since we are returning a promise from your function, then later resolving it.


JSFiddle Link - simplified demo

scniro
  • 16,844
  • 8
  • 62
  • 106