Jason Wells
Jason Wells

Reputation: 889

How do I access a returned value from a .ajax request within the done() function

Here's my function which returns a name of a person.

function getName(ID){
    return $.ajax({
        url:url,
        data: ID,
        type: 'get',
        dataType: 'json'
    });
}

And here is where I am attempting to use the .done() function.

getName("1").done() // How do I ref the returned var in our done function? 

I am confused on how to reference the returned value from my getName function within my done function.

I know I could do this using success: within the .ajax, but I am trying to move away from that and used deferred objects.

Thanks!

Upvotes: 2

Views: 225

Answers (2)

RobIII
RobIII

Reputation: 8821

It's right there in the documentation:

//Example: Save some data to the server and notify the user once it's complete.
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

//Example: Retrieve the latest version of an HTML page.
$.ajax({
  url: "test.html",
  cache: false
}).done(function( html ) {
  $("#results").append(html);
});

Also, make sure you read this, because, depending on the Datatype you might actually "receive" not a simple string/id but possibly an object parsed from a JSON/XML result or...

Upvotes: 1

dm03514
dm03514

Reputation: 55972

it look slike done requires a callback function that takes a parameter with the data recieved from teh request. http://api.jquery.com/jQuery.ajax/

getName("1").done(function(response) {
  alert(response);
}); 

Upvotes: 1

Related Questions