Home > Net >  Javascript: how i use a ''global variable'' for 2 different html pages?
Javascript: how i use a ''global variable'' for 2 different html pages?

Time:05-17

I´m using 2 different html and both use the same Javascript file.

The Javascript File does this

var problem;

function login() {
    const login = document.getElementById('login');

    const nome = document.getElementById('lnome');
    const pass = document.getElementById('lpass');

    const item = {
        Username: nome.value.trim(),
        Password: pass.value.trim()
    };
  fetch(uri, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(item)
  })
    .then(response => response.json())
    .then((res) => {
      problem = res; //HERE need to put into the 'problem' the value of the res
      window.location.href = url_1; // This calls index_2.html
    })
    .catch(error => console.error('Unable to Login.', error));
}

The above code is used in index_1.html


$(function () {
    var $users_A = $('#users_A');
        $.ajax({
            url: uri_1,
            type: 'GET',
            dataType: 'json',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Bearer '   problem);
            },
            success: function (data) {
                $users_A.append('<h4>PROBLEM RESOLVED</h4>');
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('Error in Operation');
                $users_A.append('<h4>DON'T WORK</h4>');
            }
        });
    });

The code above is used in index_2.html

When I run the program, the variable problem doesn´t not contain the information in 'res' so it gets undefined, how I resolve this problem?

Any answer is welcome

CodePudding user response:

A Global variable is only Global to the currently loaded page that uses it. It's not global to all pages that may reuse the same code. If you need data to be available to all pages for a single user, store the data in localStorage. If you need data to be shared amongst all users on all pages, you'll need to store the data on the server.

  • Related