1

Here I have global variable userId, and i want to update it inside signInUserFunction(), to use is in other function. I have tried to define it using var, window, But all these didn't help. This variable doesn't update. As i see its about AJAX async. So, what can i do with it?

And yes, I know that its not good to make authentication with JS, I am quite new to it. So, I am just creating random methods to improve.

var userId = 1;

function signInUser() {
  $.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data) {
  var items = [];
  var i = 0;
  $.each(data, function(firstname, value) {

    var str = JSON.stringify(value);
    data = JSON.parse(str);
    var innerId;
    for (p in data) {
      innerId = data[p].id;
      if ($('#nameSignIn').val() == data[p].first_name && $('#passwordSignIn').val() == data[p].password) { //
        userId = innerId;
        window.location.href = "content.html";
        break;
      } else {
        i++;
        if (i == data.length) {
          alert("Ощибка в логине или пароле!")
        }
       }
      }

    });
  });
}
Void
  • 1,129
  • 1
  • 8
  • 21
  • Why not store this information in a cookie and retrieve it/update it as necessary? – JD Davis Nov 24 '15 at 22:38
  • Why run dual loops on `data`? `$.each()` should do. Your for in loop is repetition. If `data` is an Object then how does it have a `length` property? Please indent code better. – StackSlave Nov 24 '15 at 22:38
  • {"Actors":[{"first_name":"Krasavchik","password":"1234"},{"first_name":"Kalach","password":""},{"first_name":"Bandit","password":""},{"first_name":"TestName","password":""},{"first_name":"Oleg","password":"oleg"},{"first_name":"Конь","password":"конь"}]} Its my JSON response.So it could be so.Maybe its not necessary.But its not the real problem.Method is working btw. – Void Nov 24 '15 at 22:40
  • 1
    You should loop through `data.Actors` then, not `data` – Adam Azad Nov 24 '15 at 22:41
  • @AdamAzad is correct you are not looping over the data you want, i dont actually see a key called id in your json either + you should prob not use in for loop for this either, or at least declare var p rather than use p. Use a for loop instead. (i dont use jquery but you might be overwriting your data variable as well) – David Nov 24 '15 at 22:48
  • Wheres the `data[p].id`? Should I see that in your Object that contains an Actors property, which is an Array of Objects that only have `first_name` and `password` properties? `$.getJSON()` should do just that, by the way. Why stringify and parse? – StackSlave Nov 24 '15 at 22:53
  • The outer loop is "depricated" it was my first try, but then i changed to jquery loop.And it works fine.Except userId update.I have added id field. – Void Nov 24 '15 at 22:55
  • `for( p in data){` is still in your code. – StackSlave Nov 24 '15 at 22:55
  • 1
    {"Actors":[{"first_name":"Krasavchik","password":"1234","id":1},{"first_name":"Kalach","password":"","id":2},{"first_name":"Bandit","password":"","id":3},{"first_name":"TestName","password":"","id":14},{"first_name":"Oleg","password":"oleg","id":16},{"first_name":"Конь","password":"конь","id":20}]} – Void Nov 24 '15 at 22:56
  • That's what we should be looking for. Thanks. – StackSlave Nov 24 '15 at 22:57
  • It's still doesn't work.It says that value has been changed, but after redirect it gets the default value. – Void Nov 24 '15 at 22:58

4 Answers4

0

How are you determining whether or not it has been set? It looks like immediately after you set it, you navigate to a different page. When you get to that page, you will have an entirely new window.

Try alerting the value before navigating away.

EDITED: Here is how you could pass it to the other page (but you shouldn't do this in a real app)

        window.userId=innerId;
        alert(window.userId);

        //this isn't a very secure way to do this. I DON'T recommend this
        window.location.href = "content.html?id=" + innerId ;

Then in the other page, you could access it off the document.location:

alert(document.location.toString().split("?id=")[1]);
mcgraphix
  • 2,723
  • 1
  • 11
  • 15
  • How about: alert(innerId); – mcgraphix Nov 24 '15 at 22:44
  • It's 16, but variable value is still 1. – Void Nov 24 '15 at 22:50
  • I have changed back to alert(userId).And it says it's 16.But when i am using it in method on the other page it uses default value =1. – Void Nov 24 '15 at 22:53
  • Like I said, when you get to the other page, you will have an entirely new "window" so nothing stored there will be accessible after you navigate. – mcgraphix Nov 24 '15 at 23:02
  • Even if i will change window variable to var or smth?And is there a way i could send it from one page to another with JS or URL? – Void Nov 24 '15 at 23:04
  • ***You would never want to do it this way in your real application.*** But, you could pass it in the query string to the new page: document.location='content.html?id=' + innerId; and then extract it from the location on the new page. – mcgraphix Nov 24 '15 at 23:07
  • ...also, it's worth mentioning that "window" is a bit of a misnomer. What it really means is the window of the current document. When you navigate to new pages, each one has a new "window" object. – mcgraphix Nov 24 '15 at 23:09
  • I edited my solution to show how you could pass it between pages – mcgraphix Nov 24 '15 at 23:24
0

Using the idea @mcgraphix proposed (and giving you the same warning...this would certainly not be the way to transfer data like this in a production environment), here is one way to do it:

function signInUser() {
  var url = 'http://localhost:8887/JAXRSService/webresources/generic/getAllUsers';
  var userId;

  $.getJSON(url, function(data) {
    $.each(data.Actors, function(index, actor) {
      // Cache the values of the #nameSignIn and #passwordSignIn elements
      var name = $('#nameSignIn').val();
      var password = $('#passwordSignIn').val();

      if (actor.first_name === name && actor.password === password) {
        // We have found the correct actor.
        // Extract its ID and assign it to userId.
        userId = actor.id;
        window.location.href = "content.html?userId=" + userId;
      }
    });

    // This alert should only be reached if none of the actor objects
    // has a name and password that matches your input box values.
    alert("Ощибка в логине или пароле!"); 
  });
}

// On the next page...
// Top answer from http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
// This approach can handle URLs with more than one query parameter,
// which you may potentially add in the future.
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');

    if (decodeURIComponent(pair[0]) == variable) {
      return decodeURIComponent(pair[1]);
    }
  }

  console.log('Query variable %s not found', variable);
}

var userId = getQueryVariable('userId');
0

After reading my comments, you may want to try this:

var userId = 1; 
function signInUser(){
  $.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data){
    var items = [], actors = data.Actors, l = 0;
    $.each(actors, function(i, o){
      l++;
      if($('#nameSignIn').val() === o.first_name && $('#passwordSignIn').val() === o.password){
        userId = o.id;
        // this will redirect before any other code runs -> location = 'content.html';
        if(l === actors.length){
          alert('End of Loop');
        }
      }
    });
  });
}
signInUser();

I would not store sensitive data in JSON such as passwords. Use a database. There is no need to get all the data at the same time either.

StackSlave
  • 10,613
  • 2
  • 18
  • 35
  • I understood your point, and now I at last understand how for each loop works here.But how can i send userId from one page to another? – Void Nov 24 '15 at 23:18
  • You would send data using a different AJAX function, like `$.post()`, instead of `$.getJSON()`. Set the `dataType` argument to `'JSON'`. If you want the sent information to go to another page other than the `url` argument, you will have to run another query on the othe page. Either that, or use a Session or Cookie. – StackSlave Nov 24 '15 at 23:26
  • The important thing for you to know is that JavaScript only executes on the Client when the page loads or an Event occurs. This does not mean other pages will have access to that data. If fact if you redirect, all data that is not stored in a Session or Cookie is lost. JavaScript of course loads from any page that loads. – StackSlave Nov 24 '15 at 23:34
0

Thanks you for help.Ended it all with usage of:

sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
Void
  • 1,129
  • 1
  • 8
  • 21