2

I have the following code snippet in Javascript-Jquery:

var result = "";
$.ajax({
    type: 'POST',
    url: 'update.php',
    data: { 'val': $val }
})
.done(function(data) {
    alert(data); // shows right response
    result = data;
    alert(result); // shows right response
});
alert(result); // shows nothing

Even though I initialized result in the callback, I get nothing when I alert the result variable (it is still "")? Why is this?

3
  • 1
    .done is async, bottom alert happens right away Commented Nov 27, 2013 at 3:03
  • That must be it, thanks! How do I make it .done happen before the last alert, then? Commented Nov 27, 2013 at 3:04
  • There's a way to make sync ajax call but why? Implement all your needed functionality for result inside of .done Commented Nov 27, 2013 at 3:05

3 Answers 3

3

This is because the ajax call is run asynchronously. Just because the second alert is after the ajax call, you still have to either a: write a callback method to fire when the call completes or, b: complete the ajax call synchronously. See jquery ajax documentation for the async property and its description.

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

Comments

1

Is is simple. The alert(result) code is executed before the done callback. So, the result variable is empty. The done callback is called asynchronously after the alert call.

Hope it helps.

Comments

1

This becasue the mode of ajax now you use is the Asynchronous ...i have a example for you that it's as follow:

var result = "";
$.ajax({
type: 'POST',
url: 'update.php',
data: { 'val': $val' }
}).done(function(data) {
     alert(1, data);   // shows right response
     result = data;
     alert(2, result); //shows right response
});
alert(3, result) // shows nothing

if you want to use the Synchronous...look at the doc for async variable i hope it's useful to you:)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.