Mrugesh
Mrugesh

Reputation: 4517

window.onload function is not getting called on the page

My code is as shown below:

xyz.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Status</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <div style="width: 300px;padding: 10px;margin: 0 auto;background: #f2f2f2;">
    <form name="Form">
      <input type="hidden" name="Status" value="<?php echo $_POST['Status'] ?>" />
    </form>

    <script type="text/javascript">
      alert(window.onload);
      window.onload = function() {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://api.com');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
          if (xhr.status === 200) {
            var apiresponse = JSON.parse(xhr.response);
            console.log(apiresponse);
            if (apiresponse.status == "200") {
              document.getElementById('response').innerHTML = apiresponse.message + '<br/> Press back button to continue in App.';
            } else {
              document.getElementById('response').innerHTML = JSON.stringify(apiresponse);
            }
          } else {
            document.getElementById('response').innerHTML = JSON.stringify(xhr);
          }
        };
        var elements = document.forms['Form'].elements;
        let formBody = [];
        for (var i = 0, element; element = elements[i++];) {
          let encodedKey = encodeURIComponent(element.name);
          let encodedValue = encodeURIComponent(element.value);
          formBody.push(encodedKey + "=" + encodedValue);
        }
        formBody = formBody.join("&");
        document.getElementById('request').innerHTML = formBody;
        xhr.send(formBody);
      }
    </script>
</body>

</html>

when I run the above code, in alert method I get null value and the function below it given with window.onload = function() is not getting called at all. So is there anything which needs to be included to get it done.

Upvotes: 0

Views: 267

Answers (1)

Brian Ogden
Brian Ogden

Reputation: 19232

When you call alert(window.onload) it is null because you have not assigned a function to window.onload. Your alert proves nothing.

For a sanity check, add the code alert('hello world'); above the line var xhr = new XMLHttpRequest(); in the function you bind to window.onload. You will probably find that your function is being called but its behavior is not acting as you expect, so you think your function is NOT being called on window.onload but it actually is.

Upvotes: 2

Related Questions