Ben Cameron
Ben Cameron

Reputation: 4413

Eval reference error

In javascript i am building up a string like this...

var txt = "{authenticationToken: 1, authenticated: 2, authenticationTokenExpiry: 3,sessionTimeoutMinutes: 4,userName: " + userName + "}";

This is later put through and eval statement like this...

var obj = eval('(' + txt + ')');

When this happenings I get a reference error saying the the value of the username variable is undefined.

Does anyone know the reason for this? Is it something simple that I am missing?

Upvotes: 1

Views: 968

Answers (2)

Robert
Robert

Reputation: 8767

Instead of eval(), I would suggest using the $.parseJSON() method if jQuery is available:

jQuery:

$(function(){
    var userName = 'me';

    var txt = '{"authenticationToken": 1, "authenticated": 2, "authenticationTokenExpiry": 3, "sessionTimeoutMinutes": 4, "userName": "' + userName + '"}';

    var obj = $.parseJSON(txt);
});

NOTE: The string had to be modified to satisfy the requirement of a well-formed JSON string

Demo: http://jsfiddle.net/WTC7k/

However, the reason that you're encountering the error that the value of userName is undefined is that you have to enclose the string in quotes to allow eval() to work properly:

var userName = 'me';

var txt = "{authenticationToken: 1, authenticated: 2, authenticationTokenExpiry: 3,sessionTimeoutMinutes: 4,userName: '" + userName + "'}"; 

var obj = eval('(' + txt + ')'); 

Demo: http://jsfiddle.net/9rtgK/

Upvotes: 0

dmck
dmck

Reputation: 7861

Your missing quotes around the username variable:

var txt = "{authenticationToken: 1, authenticated: 2, authenticationTokenExpiry: 3,sessionTimeoutMinutes: 4,userName: '" + userName + "'}";

I assume you want to store the string value of the username in your userName variable. Since it wasn't quoted it was treating the value of username as a variable. So for example if username was "testValue123" it would of been userName: testValue123 instead of userName: 'testValue123'

Upvotes: 1

Related Questions