简体   繁体   中英

my function can't pass it's parameter value javascript

Ive been struggling to pass my parameters from a functions but I just really can't figure out where did I go wrong. I have a function that have a parameters that I want to pass to my postData to display datas in my jQgrid. Here's my function code with parameters:

function getTID(hdrID){
  var selected = $('#editTallyHdr').val();  
  var hdrID = '';
  var hdrNo = '';

  var nameFlag=0;
  var par_ams = {
    "SessionID": $.cookie("SessionID"),
    "dataType": "data"
  };
  $.ajax({
    type: 'GET',
    url: 'processjson.php?' + $.param({path:'getData/tallyHdr',json:JSON.stringify(par_ams)}),
    dataType: primeSettings.ajaxDataType,
    success: function(data) {
      if ('error' in data)
      {
        showMessage('ERROR: ' + data["error"]["msg"]);
      }
      else{            
        $.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
          $.each(rowDataValue, function(columnIndex, rowArrayValue) {
            var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
            if (fldName == 'transaction_id'){
              hdrID = rowArrayValue; 
            }
            if (fldName == 'transaction_num'){   
              hdrNo = rowArrayValue; 
              if(selected == hdrNo){
                nameFlag =1;
              };        
            }
          });   
        }); 
      }
    }
  }); 
  return (hdrID);
} 

and here is my jQgrid code where I call that function to get it's parameter:

$("#tblPlank").jqGrid({
        url: '',                            
        datatype: 'local',
        jsonReader : {
          .
          .
          .
serializeGridData: function(postData) {

      var ctr =0;
      var filt=[];
      var c=[];      

      var jsonParams = {
      'SessionID':  $.cookie("SessionID"),
      'dataType': 'data',
      'transaction_id':getTID(hdrID),
      'filters': c,
      'lines':plank_data,      
      'recordLimit': postData.rows,
      'recordOffset': postData.rows * (postData.page - 1),
      'rowDataAsObjects': false,
      'queryRowCount': true,
      'sort_fields': postData.sidx
      };  
.
.// some code here
.
. 
      return 'json=' + JSON.stringify(jsonParams);
    },
    loadError: function(xhr, msg, e) { 
      showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
    },
    colNames:[...], 
    colModel:[      
     ........................
    ],  
    .
    .
    .
    caption: "Tally Transaction Details/Lines"

I also have another code where I want to get that parameter. Here's the last code:

var par_ams = {
    "SessionID": $.cookie("SessionID"),
    "dataType": "data",
    "transaction_id": getTID(hdrTID) 
}                                              
$('#tblPlank').setGridParam({
    url:'processjson.php?path=' + encodeURI('getData/tallyLnDtl') + '&json=' + encodeURI(JSON.stringify(par_ams)), 
    datatype: primeSettings.ajaxDataType,  
});
$('#tblPlank').trigger('reloadGrid');      

Those codes below that function getTID(hdrID) cant retrieve the parameter, it shows empty. This maybe simple to anyone, but I really need help on this.. been working with this for quite long hours.

The problem is that you're doing an ajax-request (asynchronous request). Then the function does not wait for an answer to arrive, but just continues and returns hdrID (which isn't set at the time). After that a response comes in, and the success-method is called, which sets hdrID to the appropiate value.

The common way to solve this is to execute a specific function with the desired values when the success-method is executed. It's too much code to look into, but it could go something like this:

function fetchContent(continueFunction) {
      $.ajax(params).success(function(reply) {
           // retrieve desired params from reply
           continueFunction(retrievedParameters);
      }
}

This is a very common misunderstanding. I've probably answered 15 of these questions in the last two weeks alone. An ajax call is an asynchronous call. That means that when you make the ajax call, it just STARTs the request. Then, while that request goes in the background, your code immediately keeps executing. That means that your function getTID() returns before the ajax call has even completed and it's value is not yet known. Thus, there is no way to return the response value from the ajax function when you return from getTID() as it is simply not known yet.

To work with asynchronous function calls (like ajax calls), you have to change your programming style to something that works asynchronously. In this case, the response to your ajax call is ONLY known in the success handler for the ajax all. So, you have to restructure your code to continue on with the execution of your processing and the handling of the ajax response from the success handler. If you have only a little bit of work to do, then you can put it all in the success handler. If you have a lot of work to do, then you can put all the rest of that work in a function call and call it from the success handler.

What you could do is define getTID to take in a callback to execute once it has the id, for instance

function getTID(hdrID, callback) {
    //ajax stuff....
    success: function (data) {
        // Error checks, etc 
        hdrID = //something dependent on data
        callback(hdrID); // THIS IS THE IMPORTANT PART

}

the callback will execute after the request has returned, when it is safe to use the data returned from the ajax request that will be needed in the callback. You could wrap all of the code that needs the return value of the request in the callback, for example

getTID(hdrID, function (ID) {
    var params = {
        "SessionID": $.cookie("SessionID"),
        "dataType": "data",
        "transaction_id": ID //USE ID 
    }                                              
    $('#tblPlank').setGridParam({
        url:'processjson.php?path=' + encodeURI('getData/tallyLnDtl') + '&json=' +     encodeURI(JSON.stringify(par_ams)), 
        datatype: primeSettings.ajaxDataType,   
    });
    $('#tblPlank').trigger('reloadGrid'); 
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM