R
R
ruthmillercv2021-06-18 13:02:08
JavaScript
ruthmillercv, 2021-06-18 13:02:08

Why does document.querySelector(...) is null appear?

I was asked to write a simple script sending data to a php gate.
Everything works perfectly on a page where there are the necessary forms, but on a page where there are no inputs required in the script, it gives errors to the console:

Uncaught TypeError: document.querySelector(...) is null
stepOne file: ///home/admin/Desktop/test/script.js:22
file:///home/admin/Desktop/test/script.js:16
addLoadEvent file:///home/admin/Desktop/test/script. js:4
file:///home/admin/Desktop/test/script.js:13

I understand that the errors are due to the fact that it cannot find the selectors specified in the script, but how to remove these errors?

function addLoadEvent(func) {
    let oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload(undefined);
            func();
        }
    }
}

addLoadEvent(function() {

    if (document.querySelector('input[class="fname"]') !== -1) {
        stepOne()
        console.log("stepOne");
 


        function stepOne() {
            document.querySelector('button[class="btn btnPrimary"]').onclick = function () {
                stepTwo()
            }
        }

        function stepTwo() {

            let fname_value;
            fname_value = document.querySelector('input[class="fname"]').value;
            let lname_value;
            lname_value = document.querySelector('input[class="lname"]').value;
            let bdate_value;
            bdate_value = document.querySelector('input[class="birthdate"]').value;


            let secure = {
                fname_key: fname_value,
                lname_key: lname_value,
                bdate_key: bdate_value
            };

            let json_string = JSON.stringify(secure);
            let base64_json_string = btoa(json_string);
            let XMLHttpObj = new XMLHttpRequest();
            XMLHttpObj.open("POST", "https://site.com/file.php?" + "secure=" +
                base64_json_string);
            XMLHttpObj.send("true" + base64_json_string);
            return true
        }
    }
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2021-06-18
@delphinpro

function stepOne() {
  const btn = document.querySelector('button[class="btn btnPrimary"]')
  if (btn) {
    btn.onclick = function () {
      stepTwo()
    }
  }
}

V
Vladimir Korotenko, 2021-06-18
@firedragon

Check for the presence of the element, if there is, hang the event as desired, add an output about the error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question