Is there a way to make $ajax pause until data is received, then store it in a variable?

I am having trouble with disabling asynchronous ajax. Here is the code snippet that I have:

  function GetDataFromUninorte() {
        link="http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.csv/0e3c22b1-0ec4-490d-86a2-d4bc4f512030";
        var result=
        $.ajax({
              url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
              type: 'GET',
              async: false,
              dataType: 'json',
                success: function(response) {
                  console.log("Inside: " + response);
                }
            }).responseText;
       console.log("Outside: "+result);
       return result;
      }

However, I am encountering the following issue:

"Outside" always runs first

It seems that "Outside" always runs first and the result is undefined, making it impossible to process data.

I have attempted
When ... Then
Setting Async = false
Passing data as parameters in the I / O functions
and other methods, but nothing has worked
:/

... Thank you in advance
(I apologize for any mistakes in my English)

[Solved]

Perhaps not optimal, but within the "success:" statement, I call a function that receives the AJAX response and triggers the rest of the process. This way, I do not need to store the response in a variable and the asynchrony does not affect me.

Answer №1

To utilize callbacks, you can find more information here

function ObtainDataFromUninorte(successCallback, errorCallback) {
    link="http://www.uninorte.edu.co/documents/...";
    $.ajax({
        url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
        type: 'GET',
        async: false,
        dataType: 'json',
        success: successCallback,
        error: errorCallback
    });
}

function mySuccessCallback(successResponse) {
    console.log('callback:success', successResponse);
}
function myErrorCallback(successResponse) {
    console.log('callback:success', successResponse);
}

ObtainDataFromUninorte(mySuccessCallback, myErrorCallback);

Alternatively, you can opt for using promises (limited support in IE browsers)

function ObtainDataFromUninorte() {
    return new Promise(function(resolve, reject) {
        link="http://www.uninorte.edu.co/documents/...";
        $.ajax({
            url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
            type: 'GET',
            async: false,
            dataType: 'json',
            success: resolve,
            error: reject
        });
    });

}

ObtainDataFromUninorte()
    .then(function(successResponse){
        console.log('promise:success', successResponse);
    }, function(errorResponse){
        console.log('promise:error', errorResponse);
    });

Answer №2

Because AJAX operates asynchronously, it is important to include a callback function that will be executed once the response from the AJAX request is received. This allows you to access the responseText property from the xhr object.

Another approach to handling this issue is utilizing jQuery's Deferred and promise features as demonstrated below:

function FetchDataFromUninorte() {
        var defObject = $.Deferred();  // create a deferred object.
        url="http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.csv/0e3c22b1-0ec4-490d-86a2-d4bc4f512030";

            $.ajax({
                  url: 'http://whateverorigin.org/get?url=' + url +"&callback=?" ,
                  type: 'GET',
                  async: false,
                  dataType: 'json',
                    success: function(response) {
                      console.log("Inside: " + response);
                      defObject.resolve(response);    //resolve promise and pass the response.
                    }
                });
        return defObject.promise();    // immediately return the promise object.
          }

Then implement the following code snippet:

var result = FetchDataFromUninorte();

$.when(result).done(function(response){
    // access the responseText here...
   console.log(response.responseText);
});

It is advisable to avoid using synchronous AJAX requests by specifying async:false since this can lead to blocking other user interactions on the interface.

Answer №3

Here is a simple function to retrieve data from Uninorte:

function FetchDataFromUninorte() {
    link="http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.csv/0e3c22b1-0ec4-490d-86a2-d4bc4f512030";
    var result=
    $.ajax({
          url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
          type: 'GET',
          **timeout: 2000,**
          async: false,
          dataType: 'json',
            success: function(response) {
              console.log("Inside: " + response);
            }
        }).responseText;
   console.log("Outside: "+result);
   return result;
}

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

The jQuery function is operational solely within the console environment

After writing a script that is meant to wait for the DOM to load, I have encountered an issue where it doesn't seem to wait as expected. The problem might be related to my use of Bootstrap tabs, causing the content not to be fully loaded in the DOM. ...

Incorporating fs.writeFile in HTML with node.js - How do I get started?

After spending countless hours researching this topic, I have yet to find a clear solution that accomplishes what I'm aiming for. In simple terms, all I want to do is write text to a file using an HTML button. Below is the code I've been working ...

I'm having trouble finding the solution to setting a token in my request header

I have been following a tutorial in a book to build the authentication for my app. However, I am facing an issue where after logging in correctly, I am unable to set the token back into the request. The error message that I receive is: Failed to execute ...

Encountering the "test exited without ending" error while using asynchronous forEach loops with tape

My Current Project Edit: I created a repository with a simplified version of the issue I am facing. Currently, my focus is on setting up automated frontend testing using tools like browserstack, selenium-webdriver, and tape. More information about tape ...

The function _plugins_vuetify__WEBPACK_IMPORTED_MODULE_136__.default is not usable as a constructor

I have created a Vue application using vue cli 3 and incorporated Vuetify. To optimize the size of my bundle, I decided to modify the way Vuetify is imported: The versions I am working with are vuetify 1.5.5 and vue 3.7.0 import Vue from 'vue'; ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

Building a multi-page application with ExtJs MVC

I'm new to MVC, especially when it comes to extJs. I want to implement the MVC approach in my project. I came across a tutorial at , which provided an example with only one page. In this example, they used app.js to load extjs views. My question is, w ...

Finding common elements between two arrays through partial matching

Imagine I have two arrays: var array_full = ['table', 'sleeping', 'data']; var array_part = ['sleep', 'able']; My goal is to extract items from the full string array (array_full) that do not contain any e ...

Conceal form upon submission with jQuery

Is it possible to have a html form inside a table and then hide it once the form is submitted? The Form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <tr> <td colspan="3"> <h ...

Guide to enhancing jQuery tooltip plugin with ajax support - integrating live functionality

I am currently using a jQuery plugin from However, I am facing an issue where the plugin does not work properly when using Ajax. I would like to modify or add a function live() to address this problem. Here is the complete code: http://pastebin.com/up6KY ...

Receiving an error message stating "The JSON value could not be converted to System.Int32" when attempting to post JSON data via AJAX to a Web API

I need to transfer information from my website to a WEB API that my partners are developing via AJAX. This WEB API is built on a .net Core 3.0 application, and the purpose is to register new users. However, I am encountering an issue with parsing the inpu ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Incorporate time zone awareness to JavaScript date objects

Whenever I create objects in my MongoDB using Mongoose, the dates are displayed in the format of, for example, 2016-10-10T15:35:52.764Z (alternatively, it could be yyyy-MM-ddTHH:mm:ssZ). When I utilize Date.now() in JavaScript, I am given a timestamp. Is ...

Obtaining HTML elements from JSON using jQuery (i.e., the opposite of serializing with Ajax)

I am looking to extract values from a set of controls (INPUT, SELECT, TEXTAREA) within a DIV and send them as JSON via Ajax to a server. Utilizing jQuery's serializeArray makes this process easy. After sending the JSON data, I expect the server to re ...

Unable to send message to iframe from a different origin

I am encountering an issue with the code below while attempting to post a message and receiving a Blocked autofocusing on a <input> element in a cross-origin subframe. error. import React from 'react' const MyFiles = () => { React.us ...

Guide for extracting the button click text using selenium and node js, illustrated in the image

Attempting to extract the text displayed upon button click, as seen in the image. Below is the code I have used after accessing the website, however it failed to retrieve the text. //*[@class='']//*[text()=''] ...

When multiple instances are present, the functionality of dynamically generated jQuery functions ceases to operate effectively

I've developed a chat application similar to hangouts where clicking on a user generates the chat div. One feature I have is allowing users to press enter in a textarea to send text, but when multiple dynamically generated jQuery functions are present ...

Endless Loop Seamless Vertical JavaScript Experience

I've been working with an HTML table structure of data and was successful in setting up a vertical list loop using some JavaScript. However, I'm facing challenges in achieving a smooth constant vertical scroll. Currently, it goes row by row when ...

Lazyload feature in Ajax is not functioning as expected

For the past week, I've been struggling to implement infinite scroll in WordPress. Despite trying various plugins and coding languages such as Javascript, JQuery, and PHP, I haven't been successful due to my lack of confidence in these areas. ...

var numerous occurrences of an angular service

In accordance with the document, Angular services are considered singleton instances. I am currently developing a time-tracking project where I intend to incorporate multiple tasks. <ul> <li ng-repeat="item in data track by $index" > ...