tags:

views:

64

answers:

4

How to set global variable.

    $(document).ready(function() {

        $("a.action").click(function(event) {
                var tempResponse = "";
            $.get("", function(response){
                tempResponse = response; 
            });
        alert("response " + tempResponse );
        }

        //todo use response to manipulate some data
});

I declared globa variable tempResponse. and I set in get call back function.

tempResponse = response; 

but while I try to alert the response no data displayed. I also try this solution. I change the variable declaration become $.tempResponse and change the set script become $.tempResponse = response;

But it doesn't work to.

Why this could be happened ?

+1  A: 

Because you call the alert before the variable is actually set. Remember that you are performing an asynchronous query when you call $.get. Try this instead:

$(document).ready(function() {
    $.get('/somescript.cgi', function(response){
        alert('response ' + response);
    });
});
Darin Dimitrov
I wanna use the response outside the $.get function scope. I just use alert to simplify my code.Do you have another suggestion ?
adisembiring
There's no other suggestion. You cannot use something that's not been assigned yet. You could still use the global variable to assign its value but you cannot use it immediately after the `$.get` function.
Darin Dimitrov
A: 

You are just calling your alert right after the $.get so the tempResponse is not yet ready

Patrick
this script call while a anchor link clicked $("a.action").click(function(event) {var tempResponse = "";//so on}
adisembiring
A: 

To make it work:

$(document).ready(function() {
    var tempResponse = "";
    $.get("", function(response){
        tempResponse = response; 
        alert("response " + tempResponse );
    });
});

Notice your alert is now inside the json callback function; this function does not execute until the json query is done

Erik
I wanna use the response outside the $.get function scope. I just use alert to simplify my code. Do you have another suggestion ?
adisembiring
A: 

My suggestion is you have to wait for the ajax to finish. use ajaxComplete()

if you have:

var tempResponse = "";
    $.get("ajax/test.html", function(response){
        tempResponse = response; 

    });

you could:

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    alert("response " + tempResponse );
    $(this).text('Triggered ajaxComplete handler.');
  }
});
Reigel