Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uhbc's avatar
Level 1

Set variable for JSON.

var variable = 'somevalue';

$.get(url, function(e){
console.log( e[0].variable );
});

How can i do something like this, i've tried almost everything but couldn't make it work.

-- The reason i wanna do that is that in the json output there are values like; a1, a2, a3 and i wanna get the value of a1 when its 10pm and get a2 when its 5am ect.

I get an error like : " Cannot read property 'variable' of undefined "

Thanks.

0 likes
8 replies
BishoyWagih's avatar

the error happens because the returned data from ajax request is empty. so you

can't access a variable on empty data.

make sure e holding data before printing variable ..

1 like
uhbc's avatar
Level 1

I am pretty sure that data is not empty

uhbc's avatar
Level 1

I think i accidentally used a wrong url, fixed it anyways. Here is how it looks like:

[
{
act: null,
id: "1",
a1: "1",
a2: "0",
a3: "0",
u1: "ax-1",
u2: "ax-2",
u3: "ax-3"
}
]

But still can't do what i wanna do

uhbc's avatar
Level 1

It's trying to look for a data called 'variable' from JSON.

i want something like;

var variable = 'u1';
console.log( e[0].variable  );

So, i wanna see;

"ax-1"
Cronix's avatar
Cronix
Best Answer
Level 67

try console.log( e[0][variable] );

var key = 'u1';

var data = [
{
act: null,
id: "1",
a1: "1",
a2: "0",
a3: "0",
u1: "ax-1",
u2: "ax-2",
u3: "ax-3"
}
];

console.log(data[0][key]); // outputs "ax-1" for me
console.log(data[0].key); // undefined

1 like
uhbc's avatar
Level 1

Worked, thank you.

1 like

Please or to participate in this conversation.