Let me see
Let me see

Reputation: 5094

Different values of same variable at different places in jquery

I am learning jquery an i am trying to get some data through ajax.
Here is the code

$(function () {
     var allProductsData;
     var gotProducts = new Array();
     var productsWithDelete = new Array();
     $('.addProducts').on('keyup', function (event) {
         var searchVal = $(this).val().trim();
         if (searchVal.length > 0) {
             $.ajax({
                 url: 'http://localhost/exhibition/admin/default/searchProducts',
                 data: {
                     products: $(this).val(),
                 },
                 type: 'POST',
                 dataType: 'html',
                 success: function (msg) {
                     allProductsData = msg;
                     alert(allProductsData); //No. 1 
                 }
             });
             alert(allProductsData); //No. 2
         }
         alert(allProductsData); // No. 3
     });
 });

The value i am getting back from the server is 1. As you can see that i have stored that value in a global variable allProductsData. But when i try to alert this allProductsData at 3 different places (No 1, No 2, No 3). then I get different values i.e

1 at No 1 // which is correct
undefined at No 2 // which is incorrect
1 at No 3 // which is again correct

Question

Why I am getting the undefined value there?

Upvotes: 3

Views: 150

Answers (2)

JelteF
JelteF

Reputation: 3271

The only place that you can be sure to have defined the allProductsData is in the success callback. The code after the ajax call will be evaluated once the call has been sent, not when a response has been received.

You should put all the code that needs allProductsData in a function an call that in the success callback. Otherwise you can never be sure that allProductsData is defined.

Upvotes: 1

kamil
kamil

Reputation: 3522

A in AJAX stands for Asynchronous, therefore you can't opperate on normal synchronouse calls. Alert No 1. is called after receiving response from server, it might, but also may not, be called before Alert No 2.. Then, No 2. is called and have not guarantee that it has already assigned value from ajax call. The No 3. I believe, has it's correct value because after calling No 1. and No 2. your server managed to respond to you with correct value.

In order to receive always correct value, operate on response in success function callback.

Upvotes: 3

Related Questions