F.N
F.N

Reputation: 401

Jquery - Pass a json object in a global variable

I'm trying to pass a json object from an ajax call in a variable that will be used in another function.

The thing is that if i try to console.log() that variable ($aR), it returns "undefined"

Here is the code:

$aR = '';

// Submit Data to ncbi.
// Sends form's data to classController.php
function NCBI_submit_data()
{
    $formData = $('#blastx_form').serialize();
    $php_method = 'ncbi_request';    
    $finalData = $formData + "&php_method=" + $php_method;
    $aR = ajaxReq('POST','../../classes/classController.php',$finalData,'json');
    console.log($aR);
}


// General Ajax function
function ajaxReq($method,$url,$data,$dataType)
{
    $.ajax({
        type: $method,
        url:  $url,
        async: 'false',
        data: $data,
        dataType: $dataType,
        success: function(json, textStatus, jqXHR)
        {
            $aR = json;
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('Ajax call error: '+jqXHR.status+' '+errorThrown)                
        }
    });
}

Upvotes: 0

Views: 1591

Answers (2)

user3820695
user3820695

Reputation:

By default JQuery Ajax do asynchronous call. You try to use data before it is retrieved from backend. After Ajax call JS interpreter will not wait for response and will execute:

$aR = ajaxReq('POST', ....).

The function "ajaxReq" does not return anything. So, the "$aR" value is "undefined".

The data will be available later in "success" callback, after retrieving response:

success: function(json, textStatus, jqXHR)
{
  $aR = json;
},

The callback "success" will be executed later "asynchronously".

Read about the difference between a synchronous and an asynchronous request:

What is the difference between a synchronous and an asynchronous request? (async=true/false)

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

Here's a rough timeline of $aR in your code:

// initialized
$aR = '';

// set to `undefined`, since `ajaxReq` returns nothing
$aR = ajaxReq('POST','../../classes/classController.php',$finalData,'json');

// then, later, when the `ajax` call completes:
$aR = json; 
console.log($aR);  // would do something now

If you need to do something with that value, do so from within the success handler

success: function(json, textStatus, jqXHR)
{
  $aR = json;
  doSomethingWith($aR);   
},

Or use the AJAX object returned by $.ajax():

function ajaxReq($method,$url,$data,$dataType)
{
  return $.ajax({ ... });
}

// called as
ajaxReq('POST','../../classes/classController.php',$finalData,'json').done(
  function(json) {
    $aR = json;
    // whatever else you want to do
  }
);

Upvotes: 2

Related Questions