Function with AJAX request that returns another function for JSON object handling

0

I have a function that uses AJAX to return data from a database. The data is processed and returned in JSON and, from there, I make the necessary manipulations. So:

function getData() {
    $.ajax({
        url: 'script.php',
        type: 'post',
        statusCode: {
            200: function(res) {
                res.forEach(function(data){
                    // do something
                })
            }
        }
    })
}

What I want to know is how to execute another function that handles this data returned in JSON by calling this function, like we do when we capture a click:

$('seletor').on('click', function(){
    // do something...
})

And with my function, it would be something like this (I'm not even sure if this is correct):

getData(function(){
    // do something with JSON data...
})

I do not know how to declare this function and "make it available" to be manipulated with another function.

I use state codes in HTTP headers to perform different functions in different scenarios. There is only 200 success code, and it is where I want to manipulate the JSON object returned by the AJAX request.

How to do this?

    
asked by anonymous 17.12.2018 / 22:47

2 answers

0

By the wording of your question, I think you're after setting the famous, callback . You can find a definition for callback in that answer from @Sergio on StackOverflow in Portuguese :

  

Callback is a function that is used as "callback". It is typically   passed as an argument of another function and / or called when an event   event occurs, or when a code part receives a response from   which was waiting.

NOTE: this is only an initial stretch of the answer

In this case, you will have to set the callback parameter to the getData function, and upon receiving the response, you "call" the parameter. Staying this way:

function getData(callback) { 
    $.ajax({ 
        url: 'script.php', 
        type: 'post',
        dataType: 'json'
        statusCode: { 
            200: callback
        } 
    });
}
getData(function(data) {
    //coloca o código para manipular os dados
});

The dataType option with the value "json" , guarantees that the response will be a JSON / JavaScript object.

I hope I have helped!

    
18.12.2018 / 01:08
0

As far as I understand, you want to manipulate the JSON that Ajax returns. then the method would look something like this:

function getData() {

$.ajax({
    url: 'script.php',
    type: 'post',
    statusCode: {
        200: function(res) {
            res.forEach(function(data){
                // do something
            })
        }
    }
}).done(ajaxDone)          // Funcao que trata caso a requisição ajax for completada
  .fail(ajaxFail); // função que trata caso a requisição ajax der falha

}

 function ajaxDone(data){
   /* Aqui voce trata aos dados como quiser vc pode verificar com if's
    o status do retorno isso se seu retorno contiver uma variável de status */
   if(data.status == 'OK'){
      // faz algo
   }
   if(data.status == 'ERROR'){
   // faz outra coisa
   }
 }

  function ajaxFail(error){
   /* Aqui você pode tratar o erro caso o ajax não seja concluído */

 }

Any error or question leave a comment, or if it is not tbm. : D

    
18.12.2018 / 00:28