skip to Main Content

How to return data from success response?

Here is my code:

$.ajax({
  async: 'true',
  url: 'https://exampleapi.com/product',
  type: 'GET',
  data: {page: idQuery},
  success:(response => {
    var idQuery = response.number;
  })
})

the goal is to put the variable in response (idQuery) to the data and it will become query param.
Should I using callback in success response? or any idea?

Thanks for help

3

Answers


  1. That’s correct that you would have to nest the callbacks if you wanted to do it that way. However, my understanding is that jqXHR will return a Promise-like object, which allows us to chain things together as such:

    $.ajax({
      async: 'true',
      url: 'https://exampleapi.com/product',
      type: 'GET',
      data: {page: idQuery},
    }).then(response => {
        const idQuery = response.number;
        return $.ajax(...) // your new call here
      }).then(...) // function when you're wanting to process results of second AJAX call
    
    Login or Signup to reply.
  2. Callback is an option, another option is setting the async flag false

    var response = $.ajax({
                          async: false,
                          url: 'https://exampleapi.com/product',
                          type: 'GET',
                          data: {page: idQuery}
                         }).responseText;
    var data = JSON.parse(response);
    var idQuery = data.number;
    
    Login or Signup to reply.
  3. you can create a custom function that use the response as an input param

    $.ajax({
      async: 'true',
      url: 'https://exampleapi.com/product',
      type: 'GET',
      data: {page: idQuery},
      success:(response => {
        var idQuery = response.number;
        doSomething(idQuery);
      })
    })
    
    function soSomething(idNumber){
    ...
    }
    

    i hope it works for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search