0

I am trying to use the logged in username as a global variable which can be passed to the internal forms, is there a way I can pass the logged in username variable to the other functions like below: Could anyone please help:

Fiddle

JavaScript:

    $(function() {

      function userLogin() {

        userName = $('#user').val();
        var password = $('#pass').val();
      }

     function requestDemo() {
        var userName = userName; // This should inherit the username from login function?
    }

});
Bob
  • 467
  • 6
  • 25
  • 1
    It is usually bad practice to depend on global vars like that. The answer to your question is indeed using the window object as described below, but I would advise considering rethinking the way you've organized the above to avoid needing to use the global scope. For example why do you even need to seprate the scope into those two functions? Or perhapes you could pass the username into requestDemo(username) like that? – Andrew Font Jan 30 '17 at 16:24

3 Answers3

2

You can just insert

var globalUsername = ''
var globalPass = '';

just underneath:

$(function() {

like this:

$(function() {
var globalUsername = ''
var globalPass = '';
...

or above, like this:

var globalUsername = ''
var globalPass = '';
$(function() {
...

After that, you can use these two variables on every place in your script.

Nedim Hozić
  • 1,871
  • 15
  • 15
  • note that, if you put the variable inside the closure (`$(function(){`) they are only visible inside this closure but not outside - so the variables are not globally available. – Sepultura Jan 30 '17 at 16:42
0

We already have a global variable available to us. How about we simply create variables right on the jQuery object. Then, in our various functions, we can simply check if they exist, implement them if they don't, or reference them if they do?

Looking at your fiddle, this can also be done pretty painlessly -- simply have each function that needs access to a global namespace either create or reference it.

$(function() {
  $.bob_jsNS = $.bob_jsNS || {};

  var mainurl = 'http://localhost:9000';

  /* Login User */
  $("#submit-login").click(function() {

    userLogin();
  });

  function userLogin() {
    $.bob_jsNS.user = $.bob_jsNS.user || {};
    var myUser = $.bob_jsNS.user;

    myUser.userName = $('#user').val();
    var password = $('#pass').val();

    // var data = $("#login-user").serialize();

    var data = {
      "userName": myUser.userName
    }

    $('#sdlc-gif').show();

    // I simply reference the global namespace to get the userName.
    if (myUser.userName != '' && password != '') {
    // Removed for clarity. There was code here.
    }
  }


  function requestDemo() {
    /*****
     * Any time I need access to any part of the global namespace,
     *  I should first check that it's there -- and if not, create it.
     *  These first few lines happen on any function that will need to get
     *  or set global values or functions.
     ***/
    $.bob_jsNS = $.bob_jsNS || {};
    $.bob_jsNS.user = $.bob_jsNS.user || {};
    var myUser = $.bob_jsNS.user;
    // If we don't have a username, set it blank.
    //  May not be an issue, but it may break otherwise.
    var myUser.userName = myUser.userName || "";
    var myUser.first = ('#firstName').val();
    var myUser.last = ('#lastName').val();
    var myUser.title = ('#jobTitle').val();
    var myUser.email = ('#email').val();
    var myUser.comments = ('#comments').val();
    var myUser.app1 = ('#app1').val();
    var myUser.app2 = ('#app2').val();
    var myUser.app3 = ('#app3').val();

    var data = {
      "userName": myUser.userName,
      "firstName": myUser.first,
      "lastName": myUser.last,
      "jobTitle": myUser.title,
      "email": myUser.email,
      "comments": myUser.comments,
      "app1": myUser.app1,
      "app2": myUser.app2,
      "app3": myUser.app3
    }
    /***
     * More code was here, abbreviated for clarity.
     ***/ 
  }


  /* Provide feedback form */

  $("#submit-feed").click(function() {

    provideFeedback();
  });
  /* Provide Feedback */
  function provideFeedback() {
    // var data = $("#provide-feed").serialize();
    $.bob_jsNS = $.bob_jsNS || {}
    $.bob_jsNS.user = $.bob_jsNS.user || {};


    var userName = $.bob_jsNS.user.userName || "";
    var q1 = $("input[name='group1']:checked").val();
    var q2 = $("input[name='group2']:checked").val();
    var q3 = $("input[name='group3']:checked").val();
    var q4 = $("#ans4").val();
    var q5 = $("#ans5").val();

    var data = {
      "userName": userName,
      "q1": q1,
      "q2": q2,
      "q3": q3,
      "q4": q4,
      "q5": q5
    }
  }
});
Snowmonkey
  • 3,716
  • 1
  • 16
  • 16
0

I would suggest using either localStorage or sessionStorage depending on your needs for persistence. You can read more about the differences of the two here.

With the below method, you assign the username value to your web browsers local storage, and then retrieve that value from the local storage when you need it, and you don't necessarily have to worry so much about the scope of where your variables are placed.

$(function() {

      function userLogin() {

        localStorage.setItem('username', $('#user').val());
        var password = $('#pass').val();
      }

     function requestDemo() {
        var userName = localStorage.getItem('username');
    }

});
Community
  • 1
  • 1
Adjit
  • 10,134
  • 12
  • 53
  • 98