Ali Nouman
Ali Nouman

Reputation: 3414

Scope variables in javascript,jquery

I am trying to access variable 'dimensions' in my ajax response but not able to get it. I dont want to make this variable global. Following is my code

  $(document).ready(function(){
  $('#submittext').click(function(){
   var dimensions;
   $.ajax({
     type: "GET",
     url: "bin/getcontentsize.php",
     data: findContentsize,
     success: function(response){
       //want to access dimensions here to assign response and some calculation(but not able to access it)
     }
     });
   //so i can use here
  });
  });

Upvotes: 0

Views: 86

Answers (4)

Kannika
Kannika

Reputation: 2558

Problem when you run it.

$(document).ready(function(){
    $('#submittext').click(function(){
        var dimensions="1";
        $.ajax({
            type: "GET",
            url: "bin/getcontentsize.php",
            data: findContentsize,
            success: function(response){
                dimensions = "2";
            }
        });
        //!!!!Attention
        alert(dimensions);  // result is "1", not "2"
    });
});

First, your code already ran. After that, your $.ajax starts to run.

Upvotes: 2

JaredPar
JaredPar

Reputation: 754725

In this case you can access the dimensions variable from both the ajax call back and the code immediately after starting the ajax request. The variable is accessible in both of these contexts.

What is most likely causing the problem though is the timing. The success method will run asynchronously after the ajax request is completed. It's best to view this as executing later. However the code immediately after the $.ajax call will execute immediately. Hence you won't see any effects from the success handler on the dimensions variable when it runs.

If there is code you want to run with the value of dimensions as calculated by the success method you need to call that code from the success callback. For example

$('#submittext').click(function(){

   var handleNewDimensions = function (dimensions) {
     // Code that used to be after the $.ajax line
   }

   $.ajax({
     type: "GET",
     url: "bin/getcontentsize.php",
     data: findContentsize,
     success: function(response){
       var dimensions = doTheCalculation(...);

       // Call the code which needs to deal with the new dimensions
       handleNewDimensions(dimensions);
     }
   });

Upvotes: 7

PiTheNumber
PiTheNumber

Reputation: 23542

This should work:

  $(document).ready(function(){
  $('#submittext').click(function(){
   var dimensions = 1;
   $.ajax({
     type: "GET",
     url: "bin/getcontentsize.php",
     data: findContentsize,
     success: function(response){
       alert(dimensions);
     }
     });
   //so i can use here
  });
  });

Upvotes: 1

Rok Kralj
Rok Kralj

Reputation: 48735

Assign the dimensions variable the value, and test it again:

var dimensions="sample";

Upvotes: 1

Related Questions