1

I need to set a variable to the results of an ajax query. I realise that i cannot just return result in the success function as this is an asynchronous call. but would like to achieve this will a callback function and not set to a synchronous call.

I would like to achieve something like:

myMethod: function() {
   var result = function(callback) {
      this.getResults(params)
   }
},

getResults: function(params) {
   $.ajax({
      type: 'GET',
      url: 'some/url',
      data: params,
      success: function(data) {
         callback(data).call();
      }
   });
}

Where result = data

I know my syntax is not right, I have tried so many variations and havent found something that works. Any help would be soooooo appreciated. Thank-you!

2 Answers 2

2

You're quite close. Pass the callback function to getResults.

myMethod: function() {
    this.getResults(params, callback);
},

getResults: function(params, callback) {
   $.ajax({
      type: 'GET',
      url: 'some/url',
      data: params,
      success: function(data) {
         callback(data);
      }
   });
}

Note that I removed the var result = since that's just not going to work given the asynchronicity you mentioned. If you need to perform further processing of data, it's got to happen in a callback.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! If i haven't allocated data to a variable in myMethod? Then how can i refer to it?
Sorry, did you mean callback instead of data? I don't understand.
Not sure ;) I want a variable in myMethod to equal data. data is a json response and I want to loop through it and compare it to another variable i have set in myMethod. Is that possible?
Ok. You can't do that, because of the asynchronous execution. Like I said in my answer, everything that relies on data must be passed as a callback (unless you're willing to accept synchronous execution, which you already said you're not). Take the logic that depends on data out of myMethod and put it into the callback function that you pass to getResults.
Okay. I think i may need to rethink what im trying to achieve here. At least i know the syntax of a callback now ;)
|
-1

Did you try setting async to false?

myMethod: function() {
   var result = function(callback) {
      this.getResults(params)
   }
},

getResults: function(params) {
   $.ajax({
      type: 'GET',
      async:false, //<-- Here
      url: 'some/url',
      data: params,
      success: function(data) {
         callback(data).call();
      }
   });
}

2 Comments

but would like to achieve this will a callback function and not set to a synchronous call.... and your code does not work (callback not defined, etc) don't just copy the OP's code.
The OP specifically said that they do not want to do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.