The initial ajax request may sometimes return as 'undefined' during its first call

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')

Answer №1

Make sure to include the following code snippet in your external.js file:

function makeAjaxCall(url, method = "POST", requestData) {
    console.log('Invoking function', url, method, requestData);
    let responseData = null;

    $.ajax({
        url: url,
        type: method,
        data: requestData,
        dataType: "json",
        async: false,
        success: function (response) {
            responseData = response.data;
        },
        error: function (error) {
            alert("Request failed" + JSON.stringify(error));
        },
    });
    
    console.log('Response Data:', responseData);
    return responseData;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the advantages of utilizing buffer geometries in Three.js?

I have experience using both BufferGeometry and Geometry, so I feel comfortable with either. Even when I need to make frequent modifications, I tend to lean on BufferGeometry because although the code is more verbose, it's not overly complex. Can you ...

What is the best way to retrieve the file name from the current document's URL using JavaScript?

I need help with a Javascript function that can extract the current file name without any parameters. $(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/); var current_path = RegExp.$1; if ((current_path == 'index. ...

Modifying webpage code

I am looking to develop a system where I can edit various elements such as the navbar, paragraphs, and images directly from a web page. I understand that this can be achieved with JavaScript, but I am facing the issue of my customizations reverting to defa ...

Can you provide some guidance on accessing HTTP headers while using Promises to make AJAX requests?

Currently, I am working on resolving jQuery ajax requests using bluebird.js and I have found it quite challenging to access the HTTP headers of the request. Here is a snippet of the code I am working with: Promise.resolve($.get(...)).then(function(data){ ...

What is the best method to incorporate a JavaScript object key's value into CSS styling?

I am currently working on a project in React where I'm iterating over an array of objects and displaying each object in its own card on the screen. Each object in the array has a unique hex color property, and my goal is to dynamically set the font co ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Steps for Implementing a Delay on Bootstrap Dropdown Hover

Is there a way to create a delay for the bootstrap dropdown feature while ensuring that it still appears on hover? If you want to test this, click here: http://www.bootply.com/YcVBzvXqrR This is the HTML code I'm using: <div class="container"&g ...

Matching exact multiple words with special characters using Javascript Regular Expression

My issue involves using RegExp to match multiple words with dynamic values. Whenever a special character like "(" is included, it interprets it as an expression and throws an Uncaught SyntaxError: Invalid regular expression error. let text = 'worki ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...

arrangement of django applications

After delving into some Django tutorials, it appears that all view functions must reside in a file named "views.py" and models belong in "models.py". This structure may result in having a large number of view functions in the views.py file as well as an ab ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

Sort through the JSON data and showcase it in a gridded format

I need assistance with displaying data from a JSON object in a grid based on user selections. The user should be able to select a year and make from a dropdown menu, and the corresponding data should then be filtered and displayed in a grid. For example, i ...

The functionality of AJAX is triggered only on the second click

On my index.html page, I'm attempting to implement a basic AJAX functionality. When clicking on an anchor tag, the text will be sent to a PHP page called data.php, which will then display the clicked page. The code is functional, but there seems to be ...

Guide on updating a text value using AJAX to request a PHP file without the need to refresh the webpage

Exploring the world of AJAX, I have a desire to develop a basic web application to apply my newfound knowledge practically. My goal is to calculate various percentages based on user input, and display the results on the webpage instantly using AJAX, witho ...

The value of ng-repeat list in AngularJS does not update when its value is changed by an ajax call

I am completely perplexed. Why doesn't my ng-repeat update when there is an ajax call that changes its value? I have searched through many questions and answers here, but none of them address the issue with the ajax call. Here is the HTML: <div c ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Should I use one-step or two-step email validation with ajax?

I need some clarification, please: I have been using a two-step validation process (client/server) for certain user inputs, like email (using the traditional form submission method - which involves reloading the page). If I switch to using the php-jquer ...

Ways to separate a string based on changing values in Javascript

Given this unmodifiable string: "AAACCDEEB" I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so: [['A','A','A'], ['C','C'], [ ...