Reuse ajax

9

I'm trying to reuse ajax to make it more mobile in my project. Put it in the following way waiting for an answer but no.

function _ajax(params,uri,type){
    $.ajax({
        url: uri,
        type: type,
        dataType: 'json',
        data: {params},
        success: function(data){
            return data;
        }
   });
}

Send it to call:

var result = _ajax(null,'http://','GET');
console.log(result);

console:

undefined

As I can reuse it, the answers come in JSON

    
asked by DoubleM 30.05.2018 в 21:23
source

4 answers

7

You have to use a callback like this:

function _ajax(params,uri,type, callback){
    $.ajax({
        url: uri,
        type: type,
        dataType: 'json',
        data: {params},
        success: function(data){
            callback(data);
        }
    });
}

and to call her

var callback = function(data) {
    console.log(data);
};
_ajax(null,'http://','GET', callback);
    
answered by 30.05.2018 в 21:30
5

The " problem " your request is asynchronous and as you raise it you can not work it.

function _ajax(params,uri,type){
return $.ajax({
    url: uri,
    type: type,
    dataType: 'json',
    data: params,
    success: function(data){
        console.log("satisfactorio")
        return data;
    }});
}
let data = _ajax("" ,"https://swapi.co/api/people/1" ,"GET")
console.log("resultado" , data.toString())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  

In the example you will see that it will always show first    resultado and then satisfactorio , this is known as function   asynchronous is worth the redundancy

Is there a solution?

If I list them below:

  • Callbacks : this is the most common, but when they are nested can give you code comprehension problems.

  • Promises : For my most valid, and supports all decent browsers

  •   

    I leave a link in case you want to know more about Promises

    function _ajax(params,uri,type){
    return new Promise(function (resolve, reject){
        $.ajax({
            url: uri,
            type: type,
            dataType: 'json',
            data: {params},
            success: function(data){
                resolve(data);
            },
              error: function(XMLHttpRequest, textStatus, errorThrown) { 
            reject("Status: " + textStatus); 
        }    
            
        });
        })
    }
    _ajax("" ,"https://swapi.co/api/people/1" ,"GET")
     .then(function (data) {
        console.log(data);
      })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  • Async / Await : It's a promise but more elegant implemented by EcmaScript7, and is still not compatible in some browsers
  • function _ajax(params,uri,type){
    return new Promise(function (resolve, reject){
        $.ajax({
            url: uri,
            type: type,
            dataType: 'json',
            data: {params},
            success: function(data){
                resolve(data);
            },
              error: function(XMLHttpRequest, textStatus, errorThrown) { 
            reject("Status: " + textStatus); 
        }  
            
        });
        })
    }
    async function buscar(){
    console.log(1)
    let traeme = await _ajax("" ,"https://swapi.co/api/people/1" ,"GET")
    console.log(traeme)
    }
    buscar()
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        
    answered by 31.05.2018 в 16:03
    0
    function _ajax(params,uri,type){
    return $.ajax({
        url: uri,
        type: type,
        dataType: 'json',
        data: params,
        success: function(data){
            return data;
        }});}
    

    the return and params only send an object:)

        
    answered by 30.05.2018 в 21:26
    0

    The ajax function of JQuery performs the request as asíncrona : something like in the background.

    In previous versions the JQuery allowed to make a request sincronica which allowed you to create a function that returns the data returned by the request indicating the property async:false , but due to the user experience that functionality was obsolete .

    You can try it with an earlier version of jQuery that supports this functionality, but it is not recommended.

    function _ajax(params,uri,type){
        $.ajax({
            url: uri,
            type: type,
            async: false,
            dataType: 'json',
            data: {params},
            success: function(data){
                return data;
            }
       });
    }
    

    What is done for now to reuse is what you answered @alanfcm the use of callback.

        
    answered by 30.05.2018 в 21:38