Frank
Frank

Reputation: 1864

Using javascript variables anywhere

Here's my jQuery function,

$.post("assets/scripts/chat/get_user_info.php", {UserID: UserID}, function(data){
if (data == "error") {
alertBar('negative','There was an error sending the message');
}
var username = data;
})

But I only use the "data" or "username" variable in the function itself, so how can I use it globally around the whole page?

Upvotes: 0

Views: 192

Answers (8)

Dmitry
Dmitry

Reputation: 123

Try document.username instead of username

document object is visible from everywhere

Upvotes: 0

Paul
Paul

Reputation: 2206

I assume your jQuery is wrapped in $(document).ready(); - try declaring the vars outside like this, which will make them global throughout the page:

var username, data;

$(document).ready(function() {
    $.post("assets/scripts/chat/get_user_info.php", {UserID: UserID}, function(data){
    if (data == "error") {
        alertBar('negative','There was an error sending the message');
    }
    username = data;
    })
});

Upvotes: 0

T. Stone
T. Stone

Reputation: 19495

Either

window.data = data

or

username = data

The thing is though,the $.post is asynchronous, so you won't be able to do something like...

$.post( ... )
alert(window.data);

Upvotes: 2

Nate B
Nate B

Reputation: 6344

Define variable in the global scope, outside your function.

var username, data;

$.post("assets/scripts . . .

Upvotes: 5

Jivings
Jivings

Reputation: 23260

window.username = data

Will make it a global variable. Though this is often considered bad practice.

Upvotes: 0

parapura rajkumar
parapura rajkumar

Reputation: 24413

What you can do is

  var myglobaldata = {};

$.post("assets/scripts/chat/get_user_info.php", {UserID: UserID}, function(data){
if (data == "error") {
alertBar('negative','There was an error sending the message');
}
  myglobaldata.username = data;
})

Now you can access myglobaldata.username from anywhere.

Upvotes: 1

Didier Ghys
Didier Ghys

Reputation: 30666

You could save it as data using .data():

$.post("assets/scripts/chat/get_user_info.php", {UserID: UserID}, function(data){
    if (data == "error") {
        alertBar('negative','There was an error sending the message');
    } else {
        $(document).data('userInfo', data);
    }
});

Then you can access it by doing:

var userInfo = $(document).data('userInfo');

Upvotes: 0

yeomandev
yeomandev

Reputation: 11806

Try

var globalData;
var username;

$.post("assets/scripts/chat/get_user_info.php", {UserID: UserID}, function(data){
    if (data == "error") {
        alertBar('negative','There was an error sending the message');
    }
    globalData = data
    username = data;
})

Upvotes: 1

Related Questions