Chud37
Chud37

Reputation: 5007

Getting data from PHP script using $.get

I am just trying to get the data returned (from a php script, the script is working fine)

$.post(
    "http://labs.*********.com/inc/ajax/till_status.php",
     {
          id:$("#potentialID").val()
     }
).done( function (data) {
    currentTillStatus = data;
});

And I want it to be placed into the variabled called currentTillStatus.

Where am I going wrong?

Okay, full code is here:

function checkStatus() {
    var currentTillStatus = null;
    $.post(
        "http://labs.*****.com/inc/ajax/till_status.php",
        {
            id:$("#potentialID").val()
    }).done(function (data) {
        currentTillStatus = data;
    });
    console.log("Till Status: " + currentTillStatus);
}


$(document).ready(function () {

    checkStatus();  
    setInterval(checkStatus,1000);

});

And result:

Till Status: null

Upvotes: 0

Views: 47

Answers (2)

Boaz
Boaz

Reputation: 20230

By default, jQuery's AJAX requests are asynchronous, so unless you've changed them to be synchronous (e.g. with ajaxSetup()), the console.log() call is made before the request is completed and the done callback is triggered, leaving currentTillStatus as null.

Consider moving the console.log() call into the done callback.

Upvotes: 2

Abu Romaïssae
Abu Romaïssae

Reputation: 3901

what you can probably do is:

function outputStatus( currentTillStatus ){
    console.log("Till Status: " + currentTillStatus);
}

function checkStatus() {
    $.post(
        "http://labs.*****.com/inc/ajax/till_status.php",
        {
            id:$("#potentialID").val()
    }).done(function (data) {
        outputStatus( data );
    });
}


$(document).ready(function () {

    checkStatus();  
    setInterval(checkStatus,1000);

});

Answer made before posting full source code


Make sure you define the currentTillStatus variable in the outside scope like

var currentTillStatus;
$.post(
    "http://labs.*********.com/inc/ajax/till_status.php",
     {
          id:$("#potentialID").val()
     }
).done( function (data) {
    currentTillStatus = data;
});

Upvotes: 1

Related Questions