AJAX request function that returns another function for JSON object manipulation

Asked

Viewed 259 times

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 do the proper 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 perform another function that handles this data returned in JSON when calling this function, like we do when capturing a click:

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

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

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

I don’t know how to declare this function and "make" this object to be manipulated with another function.

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

How to do this?

  • It was bad, it was for another question, I posted wrong

  • regardless of the code, you want to execute a function at the end of the ajax request?

  • In the request response, you are expecting an array?

2 answers

0

As I understand Voce wants to manipulate the JSON that Ajax returns. then the method would be more or less 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 doubt leave a comment, or if it is not that tbm. : D

  • This is very useful... But I don’t want to manipulate the return of JSON in different ways, so I wanted to know how to return the data and use it in any callback function. But thanks for your help!

0


By the utterance of your question, I think you’re behind defining the famous, callback. You can find a definition for callback in that reply by @Sergio himself Stackoverflow in English:

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

NOTE: this is only an initial part of the answer

In case, you will have to set the parameter callback for the function getData, and in receiving the reply, you "call" the parameter. Thus staying:

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 option dataType with the value "json", ensures that the answer will be a JSON/Javascript object.

I hope I’ve helped!

  • It was so easy and I got lost all... Thanks! = D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.