Question

I am currently using a login function on my page, with that i wanna use the username submitted somewhere else to use this for other purposes.

My login javascript file is as following

$(document).ready(function() {

    $("#submit").click(function() {
        console.log("click");

        var jsonp = {
              username: $("#username").val(),
              password: $("#password").val(),
              is_ajax: 1
        };

        $.ajax({
            type: "POST",
            url: "http://myurl.com/login.php",
            data: jsonp,
            success: function(response) {
                if (response == 'success') {
                     window.location = "homepage.html";

                } else {
                     alert("wrong username password combination")
                }
            }
        });

        return false;
    });
});

In this same file i wanna use the username that is submitted for other purposes so outside of that function. How can i do that?

Was it helpful?

Solution

If you don't want to use any Server languages. You can just use window.localStorage.setItem('username', theUsernameFromOtherThing); as suggested by @Paul S

However if you want also want to use a server language(such as PHP) I recommend a cookie, but beware of storing secure data in a cookie, since anyone sniffing can just grab it.

Also if you are sending you username and password to a url on another server, you better check that your domain, and the domain you are posting to, starts with https.

I highly recommend Sitepoint for their very simplified guides. http://www.sitepoint.com/how-to-deal-with-cookies-in-javascript/ if you wan't to learn basic web development.

OTHER TIPS

Use jquery cookie plugin, the link as working today: https://github.com/carhartl/jquery-cookie

Create session cookie:

$.cookie('the_cookie', 'the_value');

Create expiring cookie, 7 days from then:

$.cookie('the_cookie', 'the_value', { expires: 7 });

Create expiring cookie, valid across entire site:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

Read cookie:

$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

Read all available cookies:

$.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }

Delete cookie:

// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('the_cookie');

// Same path as when the cookie was written...
$.removeCookie('the_cookie', { path: '/' });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top