1

Im having an issue assigning a string to a variable and then returning it. It sounds simple and should be but im completely lost as to why what is happening is happening. My code:

function drawpills() {
    var picid;
    $.post('js/fetchdata.php', function (data) {
        var clock = document.getElementById('clock');
        clock.innerHTML = "<img src='images/clock/pill.png' alt='pill_image' id='pillpic" + data + "'/>";
        picid = "pillpic" + data;
        alert(picid); //if i run it here i get pillpic31 which is what i want
    });
    alert(picid); //if i run it here i get undefined which is not what i want and which is what is being returned
    return picid;
}

I highlighted the issue with comments on the respective line. Any help is appriecated.

Ben
  • 2,518
  • 4
  • 18
  • 31
  • 1
    This is normal behaviour. Please bare in mind that Ajax request is asynchronous and execute callback function when the request is completed. – VisioN Dec 15 '13 at 17:58
  • 2
    visit http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Satpal Dec 15 '13 at 17:58
  • well this is my answer so thanks – Ben Dec 15 '13 at 18:01

3 Answers3

2

Suggest you read through the linked article in comments.

What you need is something like this:

function drawpills(callback){
    var picid;
    $.post('js/fetchdata.php', function(data){
        var pcid = data; // process pcid here
        callback(pcid);
     });
}
Captain John
  • 1,859
  • 2
  • 16
  • 30
0

The problem is the asynchronous behavior of AJAX. When the AJAX response is sent, it moves onto the next statement, whether or not the call has finished executing. You can now do one of two things. You could either make the AJAX synchronous, which will probably break the timing of events on the page, or you could create a callback to be executed when the AJAX call is completely finished.

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
0

$.post callback is asynchronous function,so:

function drawpills(){
  var picid;
  var callback = function(data){
    var clock = document.getElementById('clock');
    clock.innerHTML="<img src='images/clock/pill.png' alt='pill_image' id='pillpic"+data+"'/>";
     picid="pillpic"+data;
     alert(picid);
    }
    $.post('js/fetchdata.php', callback);
    //picid is undefined,because callback is running until server response data.
    //unless you using synchronous request
    alert(picid); 
    return  picid;
}
yoyo
  • 722
  • 6
  • 4