1

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?

Ben Cameron
  • 4,335
  • 6
  • 51
  • 77

2 Answers2

1

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'

dmck
  • 7,801
  • 7
  • 43
  • 79
0

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/

Robert
  • 8,717
  • 2
  • 27
  • 34
  • Yes that would be ideal but sadly this code is for a Blackberry application on an older model. JSON.parse isn't available. – Ben Cameron Jul 09 '12 at 07:27