Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
How can I store the result of an AJAX query in a pre-declared variable?
$("#btn").click(function() {
    var data;
    getData();
    // use data...
}

function getData() {
    $.ajax({
        // Usual AJAX key-value pairs...
        success: function(response) {
            // Set data = response
        }
    });
}

How can I store the response to the AJAX request in the data variable declared in the handler function?

I want to use the value returned by the server inside the handler function.

Is there a way I can do this without disabling asynchronous retrieval.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Based on what you are asking, you could do the following, but I would suggest running your logic inside of the callback itself, as Javascript will not wait for the ajax response to complete before moving on within the function.

var getData = function( callback ) {

    $.ajax({
        success: function( response ) {

            callback( response );

        }
    });

};

$('#btn').on('click', function(evt) {

    var data;

    getData(function(response) {
        data = response;

        //you should use data here

    });

});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!