I have been working on creating a text input help feature similar to a desktop using the datatable.in table with keyboard navigation. In order to achieve this, I am dynamically changing the data source and also altering the header column. I have been successful in accomplishing this task except for obtaining dynamic column headers.
To fetch the column header based on the text input header, I am making an ajax call to retrieve the list of column headers. The issue arises when the first ajax call returns undefined
, but it displays the value during the second call. I understand that this is due to the asynchronous nature of the call, but I am unsure how to resolve it.
Below are snippets of my code:
AJAX call in external .js
function ajaxCall(ipUrl, callType = "POST", dataIn) {
return $.ajax({
url: ipUrl,
type: callType,
data: dataIn,
dataType: "json",
success: function (response) {
retData = response.data;
alert('success'+ retData);
return retData;
}, error: function (err) {
alert("fail" + JSON.stringify(err));
}, //error
});
}
HTML Script tag
$("#btn").click( function (e) {
var tData = { action: 'getHeader',
csrfmiddlewaretoken: 'Gys4TSx3ODJLcMDuXlSvS7DopVZr1HWEDLg9AlJsARXp7wmUGAxxKwo6uLVXIrf2',
}
tmp = ajaxCall('dyncolheader','GET',tData) ;
if (tmp == undefined) {
alert('second call');
tmp = ajaxCall('dyncolheader','GET',tData) ;
alert('tmp' + tmp);
} else {
alert('else' + tmp);
}
});
Django View code
def dyncolheader(request):
hrdText = 'First,Second,Third'
if request.is_ajax and request.method == 'GET':
print('ajax call')
if request.GET.get('action') == 'getHeader':
print('get header')
return JsonResponse({ 'data': hrdText }, status=200)
return render(request, 'dyncolheader.html')