function $ .Ajax () return value?

9

this is the code:

var res = VerFileRepetidoBancoAjax( "teste" );
console.log("res="+res);

function VerFileRepetidoBancoAjax( str ){
 $.ajax({
    url:    "caminho.",
    type:   "get",
    dataType:"json",
    data:   "dado="+ str,
    async: false,

    success: function( data ){
        return data;           
    }
});
}

In this case I need the return value of the Ajax function, which always returns undefined . This function returns a small Json object that will later be manipulated elsewhere.

By hour, to solve this issue I used a public variable, it follows:

/* declaro uma variavel publica */
var res ;
VerFileRepetidoBancoAjax( "teste" );
console.log("res = "+res);

function VerFileRepetidoBancoAjax( str ){
 $.ajax({
    url:    "caminho.",
    type:   "get",
    dataType:"json",
    data:   "dado="+ str,
    async: false,

    success: function( data ){
        /* aqui coloca o OBJ dentro da variavel publica*/
        res = data;           
    }
});
}

There is a form inside the function $ .ajax ();

    
asked by anonymous 18.08.2014 / 17:05

3 answers

3

The value returned is in the data parameter of your callback function on success:

success: function( data ){
    console.log("data ="+data );      
}

The call $.ajax itself is asynchronous by default (% with%), and its function async: true is not returning anything.

    
18.08.2014 / 17:13
2

You are returning the date into the function, but it does not return anything outside it, so try:

var res = VerFileRepetidoBancoAjax( "teste" );
console.log("res="+res);

function VerFileRepetidoBancoAjax( str ){
 var retorno;
 $.ajax({
    url:    "caminho.",
    type:   "get",
    dataType:"json",
    data:   "dado="+ str,
    async: false,

    success: function( data ){
        retorno = data;           
    }
});
return retorno;
}
    
18.08.2014 / 17:32
1

The use of synchronous ajax requests is discouraged, probably something like this will appear on your console: Synchronous XMLHttpRequest should not be used on the main thread because of its detrimental effects to the user experience. For more information link .

What can be done in these cases is to use callback, its function would look something like this:

function VerFileRepetidoBancoAjax( str, response, err ){
    $.ajax({
        url:    "caminho.",
        type:   "get",
        dataType:"json",
        data:   "dado="+ str,

        success: function( data ) {
            response(data);   
        },

        error: function (request, status, error) {
            err(request.responseText);
        }
    });
}

And would use it as follows:

 VerFileRepetidoBancoAjax( "teste", function (response) {
      console.log(response);
 }, function (error) {
     console.log(error);
 });
    
07.02.2017 / 17:52