0

Got the following code:

$('#next_btn').click(function() {
  addUser();
}); //$('#next_btn').click

function addUser() {
  var participant = {};
  var PID = 0;
  PID = FindUserByEmail($('#UserEmail').val());
  // do other things and add this user's data to the participant JSON object
} // function addUser()

function FindUserByEmail(user_email) {
  var url = escape(AJAX_URL_SELECTBYEMAIL + user_email);
  $.ajax({async: true
        , type:'POST'
        , url: url
        , dataType: 'json'
        , success: ajax_find_user_result 
        , error: ajax_error   
        }); // $.ajax
} // function FindUserByEmail(user_email)

function ajax_error(jqXHR, textStatus, errorThrown) {
  alert('X:' + jqXHR.status);
  alert('E:' + thrownError);
} // function ajax_error(jqXHR, textStatus, errorThrown)

function ajax_find_user_result(data) {
  if(data.result) {
    pid = data.result.PID;
    if (pid == 0) {
      alert('User not found');
      return false;
    } else {
      alert(pid);
    } // if (pid == 0)
  } else {
    alert('No results returned');
    return false;
  } // if(data.result)
} // function ajax_find_user_result(data)

The addUser() function is called from the click event. How can I make sure that the function FindUserByEmail returns the value from the ajax call? I am not sure how to do this.

Calling the URL by itself returns correct JSON and a demo returns the correct PID. Just not sure how to do it like above.

mleko
  • 11,650
  • 6
  • 50
  • 71
MB34
  • 4,210
  • 12
  • 59
  • 110

3 Answers3

2

The first 'A' in AJAX means "asynchronous", which means that the result comes back after the call to $.ajax() returns. All processing of the result must be done in ajax_find_user_result.

Note that this isn't a limitation. It's actually a good thing, since it means your browser won't hang waiting for the result to come back. (There are other ways to solve this problem, but callbacks is the way it's done in JavaScript, and AJAX in particular.) If you really, really want to do synchronous calls, set async=false in the parameters, but you really, really shouldn't do this (plus, it isn't supported in some cases).

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
0

You could do the work in your success handler, or use jQuery's .when()/.then() methods.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

How about this?

function FindUserByEmail(user_email) {
  var url = escape(AJAX_URL_SELECTBYEMAIL + user_email);
  $.ajax({async: true
      , type:'GET'
      , url: url
      , dataType: 'json'
      , success: function(data) {
        if(data.result){
          pid = data.result.PID;
          if(pid == 0) {
            return -1;
          } else {
            return pid;
          }
        } else {
          return -2;
        }
      }
      , error: ajax_error   
      }); // $.ajax
} // function FindUserByEmail(user_email)
MB34
  • 4,210
  • 12
  • 59
  • 110