Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

jQuery.ajax(), how to handle response 1

Status
Not open for further replies.

erichfosse

IS-IT--Management
Jun 9, 2008
11
NO
I've been experimenting with jQuery.ajax(), and I have come to the conclusion that everything in the scope of the .done()-function in the ajax-call is contained within the scope of the .done()-function, and cannot be accessed from the outside.
I've also tried passing a callback function, but all variables in the callback function are contained within the callback function.
It has come to my understanding that "pass by reference" is not possible with JavaScript.

In the end, what I did was this:

Code:
var APICall = function(settings){
  if(settings.error === null){
    $.ajax({
      type: "GET",
      url: settings.url,
      cache: false,
      dataType: 'json'
    }).done(function(response){
      $("body").append('<div id="response" style="display: none;" />'); // Adding response to a hidden DOM element
      $("#response").attr("response", JSON.stringify(response));
    }).fail(function(XMLHttpRequest, textStatus, errorThrown){
      // Handle errors here
      console.log(XMLHttpRequest);
      console.log(textStatus);
      console.log(errorThrown);
    });
  }
}

Then I got the response from the DOM, and removed the temporary element.

Is this a "valid" way to do it?
It seems a bit messy..

Thanks for all responses!

Regards, Erich Fosse
 
global variables are accessible in the local scope.
for dealing with variables inside anonymous functions you should research closures. Be a bit aware to the fact that you need to double nest the functions within a callback if using closures within a loop (and sometimes anyway).

eg.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top