0

when i call this function I am not getting a return value to use in my other function that called it. I know this request works as I can use alert() and see the value is there. Any ideas would be greatly appreciated.

function GetRepName(InputStr1){
  var name = '';
  $.post("getrepname.php", {queryString: ""+InputStr1+""}, function(data){
    if(data.length >0) {
      $('#Results'+InputStr1).html(data);
      name = data;
    }
  });
  return name;
}

The posts I have read so far suggest having the variable defined in the outer function and then returned but this doesn't seem to be working. do I need to add some code that will wait for the value to be returned before issuing the return statement?

2
  • 3
    This is due to the nature of asynchronous requests. Have a search, this question has been asked literally hundreds of times. Commented May 21, 2012 at 14:12
  • ...or look at the related questions in the right column.
    – Guffa
    Commented May 21, 2012 at 14:17

3 Answers 3

2

The thing is that the $.post callback is called asynchronously, i.e. after the function has returned. You could make the AJAX call synchronously, but this isn't recommended. You are better off re-designing your code taking into account the asynchronous nature of requests.

1

This might solve your problem, because this way the script will stops until it will get the result:

$.ajaxSetup({async:false});

Note that ajax is not designed for this, it should be asynchronous, as its name shows it: Asynchronous JavaScript and XML


I show you how I would do it:

function fnA(){
   GetRepName();
}

function GetRepName(InputStr1){
  var name = '';
  $.post("getrepname.php", {queryString: ""+InputStr1+""}, function(data){
    if(data.length >0) {
      $('#Results'+InputStr1).html(data);
      name = data;
    }
    //fnB will be called if the ajaxing finished
    fnB(name);
  });
}

function fnB(name)
{
   //do something with name
}
0

If the wonderful answers here, seems technical/confusing to you. I've divided the code into segments (parts). Look at comments.

function GetRepName(InputStr1){
  var name = '';   // Part1 (runs immediately when you call function)
  $.post("getrepname.php", {queryString: ""+InputStr1+""},  // Part2 (runs immediately after Part1, an ajax request is called by client to server
function(data){ 
    //Part3 (Javascript does an ajax call to server, server executes its code and then send the result back to client, only then the below part of code executes....(i.e. when server sends its response))
    if(data.length >0) {    
      $('#Results'+InputStr1).html(data);
      name = data;
    }

  } /* end of part 3 */); 
  return name;    // Part4 (runs immediately after part2
}

Since Part4 runs before part3, name='' is sent when you call GetRepName("your_string");

Not the answer you're looking for? Browse other questions tagged or ask your own question.