Using JQuery how to get the response from an ajax call?

  Tags: , ,


I currently have this function:

function devuelveButaca(posicion){
    var array = posicion.split('_');
    var row = array[0];
    var column = array[1];
    var planta = $('#plantaField').val();
    var resultado = "";
        type : 'GET',
        url : 'site/numButaca',
        data : {
            planta : planta,
            column : column,
            row : row
        success : function(data) {
            if(data == 'undefined' || data == ''){
                resultado = column;

                resultado = data;
        error : function(request, status, error) {

    return resultado;

Which returns the result correctly, the problem is that unless you enter debug mode, or put an alert before the return, it resultadoreturns empty. Currently, the alert is empty but returns the result correctly (I use it to add the text of the variable to a div).

I have read that you can fix it by setting a Timeout, but I would like to know if there is any more elegant solution than this.

Solution for getting the response from an ajax call using JQuery:

Explanation of the problem


The A in Ajax means Asynchronous; this means that the request is outside the normal flow of execution. In your code the $.ajax, when executed, continues the return,, return resultadoand this is executed before the ajax function or request passes the value of the response to the success. Therefore when you use the alert it returns empty or undefined, since the request you made has not returned.

Possible solutions that you can give to your problem:

Use callback functions: A callback is a function that will be invoked later when the Ajax request has finished.


function hacerPeticionAjax(url, callback) { // callback es solo el nombre de la variable
    $.ajax(url, {
        // ...
        success: callback,
        // ...

function alRecibirAnimales(animales) {
  // animales contendrá la respuesta al ajax

hacerPeticionAjax('/api/animales', alRecibirAnimales);

This example demonstrates that the property successmust receive a function, which jQuery will invoke upon completion of the request if successful. By the way, there is another callback available to control what to do in case of errors. It is managed using the property error; receives a callback that will be invoked in case of non-success.

Use the promises:

The promises are containers of future values. When a promise receives the value if it was resolved or canceled, it will notify listeners who want to access that returned value. One of the added values ​​is that it has a higher code reading and in my opinion it is a much better approach. Example:

function delay() {
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {
    // Only `delay` is able to resolve or reject the promise
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);

delay().then(function(v) { // `delay` returns a promise
  console.log(v); // Log the value once it is resolved
}).catch(function(v) {
  // Or do something else if it is rejected 
  // (it would not happen in this example, since `reject` is not called).

Use Jquery Deferred

This is a customized implementation of the promises implemented by jQuery; The use is very similar to the point explained above:

function ajax() {
    return $.ajax(...);

ajax().done(function(result) {
    // Code depending on result
}).fail(function() {
    // An error occurred