'Order of scripts and php variables for AJAX post on a page (loading order)

I have a question regarding the order of where to place a script and a variable. The reason is that I thought if you have a function and you call it after the page is loaded it will be "found" and executed.

I have a simple POST example, two php pages, the php variable is set before the script:

<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="/digiblox/css/style.php" rel="stylesheet">

<script src="/digiblox/functions/jquery-3.6.0.js"></script>

<script>
<?php $startRow2send = rand(); ?>
function firstPage() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("ajaxCall").innerHTML = this.responseText;
    }
  xhttp.open("POST", "postRec.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("startRow2send=" +<?php echo $startRow2send; ?>);
}
</script>

</head>

And the body of this page:

<body>
    <p>
    <div><button type="button" onclick="firstPage()">Test ajax call</button> </div>
    </p>
<div id="ajaxCall">
</div>

</body>


</html>

So this works, it calls a simple page and outputs "The value sent by POST method is :" and the value.

My question is, if I put the php variable set further down, say in the body of the page, then the script doesn't work.

If I put the script at the bottom of the page, it works.So like with php include it basically gets read in the order it appears in the code, understandable but surely the point of a function or script is to declare it and it gets called when the button is pushed.

Is there a way to keep the scripts, functions in the header sections and call them with loaded variables that are only loaded after the script is loaded.

And at the same time, shouldn't the button "refresh" the Ajax call each time?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source