Why does Javascript function run without being called??

Why does Javascript function DateDifff run without being called??
Even more interesting to me is that unassigned variables are throwing errors that are inside logic blocks that should not run (since the logic condition is not true)
So how is this running? Even if I did something to cause it to run; why it is executing logic with IF statement which is not true?

Are all variables checked for values when a page is loaded? Seems odd...Error
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
    <script type="text/javascript">
        $(window).on('load', function() //Runs After page loads. We want to compute Column totals
            // We get a cell's value/text(html) based upon id of column and row
        {
            var Column1Tot = 0 ;
            // Lets start totaling Scenerio1
            var column = $('#Scenerio2').index(); // This is the column # (index/screnerio). this ID is found in the <col> tag
                                                  // When a column can NOT be found it seems to use the last column
            var cell = $('#RecordingFees').find('td').eq(column); // Here we get the row whose ID is found in <td> tag and a coulm for that row found directly above
            //alert( "rECORDINGfEESXXX = " +  parseFloat(cell.html())   ); // If row ID does not exist , we get Nan error
            Column1Tot +=  parseFloat(cell.html());
            var cell = $('#Commissions').find('td').eq(column);
            //alert(parseFloat(cell.html())   );
            Column1Tot +=  parseFloat(cell.html()); // Take previous Column1Tot value and add to it using += operand
            //alert("Column Total " + Column1Tot);

        });
    </script>

    <script type="text/javascript">
    function datedifff(type, scenerio) // scenerio # is 1,2 or 3. type is "RETax"
    {
        var RETaxPaidThru = new Date();

        if (scenerio === 1 && type === "RETax") {
            RETaxYearPaidThru =  <?php echo $_POST['PTaxYear1']; ?>;
            ClosingDate = new Date("<?php echo $_POST['closingdate1']; ?>"); //quotes required around text date
            // Seperatley assigning date text to date field did not work, it seemed to convert the date field back to a text field so above I created and assigned date in one step.
        }
        else if (scenerio === 2 && type === "RETax"){
            RETaxYearPaidThru =  <?php echo $_POST['PTaxYear2']; ?>;
            ClosingDate = new Date("<?php echo $_POST['closingdate2']; ?>");
        }
        else if (scenerio === 3 && type === "RETax"){
        RETaxYearPaidThru =  <?php echo $_POST['PTaxYear3']; ?>;
        ClosingDate = new Date("<?php echo $_POST['closingdate3']; ?>");
        }

        RETaxPaidThru.setMonth(11); //Month is base 0, so DEC = 11 !
        RETaxPaidThru.setDate(31);
        RETaxPaidThru.setFullYear(RETaxYearPaidThru);

        // The number of milliseconds in one day
        var ONE_DAY = 1000 * 60 * 60 * 24;

        // Convert both dates to milliseconds
        var RETaxPaidThru_ms = RETaxPaidThru.getTime();
        var ClosingDate_ms = ClosingDate.getTime();

        // Calculate the difference in milliseconds
        var difference_ms = Math.abs(RETaxPaidThru_ms - ClosingDate_ms);

        // Convert back to days and return
        return Math.round(difference_ms/ONE_DAY);

    }
    </script>

Open in new window

swendellAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Olaf DoschkeSoftware DeveloperCommented:
What you see there is a code parsing error, not code execution error.

The PHP variable  $_POST['PTaxYear2'] seems not to be set, so your JS code ends up as
RETaxYearPaidThru =  ;

Open in new window

as shown in the highlighted line 36.That line simply is syntax error, an assignment needs a value.

Again, the main point is, if a browser encounters JS code, that's parsed, maybe even "precompiled" or prepared when first read, as JS has become an important part of websites and browsers compete with the best execution of websites.So such syntaxc errors will appear in the console, even though most of the time this is simply suppressed for the end user. It's not an execution error, but rather a compile error.

So you have to have valid code in JS even in cases not encountered. If you already know in your PHP script, which branch will later run, ou could of course also throw away JS code that doesn't get executed anyway and write out the code, which will be excuted anyway, dynamically.

Though that's not what I'd call advanced and best practice. You only profit of caching, if your JS code is static and gets its values/initializations the usual way at variable creation or calls from HTML elements or events.

Without lookin deep into thous, you might rething writing your PHP values into JS code this way.

Bye, Olaf.
1
Michael VasilevskySolutions ArchitectCommented:
You're seeing a syntax error. The browser parses the JavaScript code when it loads a page. This is separate from executing/running the code.
0
swendellAuthor Commented:
1. Ok parsing on load, no error to end user, got it. Some values are not posted to this receiving page from the sending page. So for example: $_POST['PTaxYear3'] is empty

2. Now when I try to call the function; I get an undefined error, maybe because the page load parsing is stopping subsequent code from running ? Am I missing something obvious?

Image-11.png
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Michael VasilevskySolutions ArchitectCommented:
Your code must parse with valid syntax in order for the page to load. Correct all syntax errors before proceeding.
0
swendellAuthor Commented:
Still struggling.
1) I noticed the variables on form were not being posted, I fixed that but now I am having more basic issues with scope of JS variables
I am trying everything and now likely messing up more then I am fixing...
My post returns properly as 2018 BUT it wont assign to variable RETaxYearPaidThru
Image-12.png
 <script type="text/javascript">
        var RETaxPaidThru = new Date();
       // var RETaxYearPaidThru;
    function datedifff(type, scenerio) // scenerio # is 1,2 or 3. type is "RETax"
    {

        //ClosingDate = new Date();

        if (scenerio === 1 && type === "RETax") {
            var RETaxYearPaidThru =  <?php echo $_POST['PTaxYear1']; ?>;
            ClosingDate =  new Date("<?php echo $_POST['closingdate1']; ?>"); //quotes required around text date
            // Seperatley assigning date text to date field did not work, it seemed to convert the date field back to a text field so above I created and assigned date in one step.
        }
        else if (scenerio === 2 && type === "RETax"){
            var RETaxYearPaidThru =  <?php echo $_POST['PTaxYear2']; ?>;
            ClosingDate = new Date("<?php echo $_POST['closingdate2']; ?>");
        }
        else if (scenerio === 3 && type === "RETax"){
        var RETaxYearPaidThru =  <?php echo $_POST['PTaxYear3']; ?>;
        ClosingDate = new Date("<?php echo $_POST['closingdate3']; ?>");
        }

        RETaxPaidThru.setMonth(11); //Month is base 0, so DEC = 11 !
        RETaxPaidThru.setDate(31);
        RETaxPaidThru.setFullYear(RETaxYearPaidThru);

        // The number of milliseconds in one day
        var ONE_DAY = 1000 * 60 * 60 * 24;

        // Convert both dates to milliseconds
        var RETaxPaidThru_ms = RETaxPaidThru.getTime();
        var ClosingDate_ms = ClosingDate.getTime();

        // Calculate the difference in milliseconds
        var difference_ms = Math.abs(RETaxPaidThru_ms - ClosingDate_ms);

        // Convert back to days and return
        return Math.round(difference_ms/ONE_DAY);

    }
    </script>

Open in new window

0
Michael VasilevskySolutions ArchitectCommented:
You should only declare the variable once, e.g.:

<script type="text/javascript">
    var RETaxPaidThru = new Date();
    var RETaxYearPaidThru;
    function datedifff(type, scenerio) // scenerio # is 1,2 or 3. type is "RETax"
    {

        //ClosingDate = new Date();

        if (scenerio === 1 && type === "RETax") {
            RETaxYearPaidThru = <?php echo $_POST['PTaxYear1']; ?>;
            ClosingDate = new Date("<?php echo $_POST['closingdate1']; ?>"); //quotes required around text date
            // Seperatley assigning date text to date field did not work, it seemed to convert the date field back to a text field so above I created and assigned date in one step.
        } else if (scenerio === 2 && type === "RETax") {
            RETaxYearPaidThru = <?php echo $_POST['PTaxYear2']; ?>;
            ClosingDate = new Date("<?php echo $_POST['closingdate2']; ?>");
        } else if (scenerio === 3 && type === "RETax") {
            RETaxYearPaidThru = <?php echo $_POST['PTaxYear3']; ?>;
            ClosingDate = new Date("<?php echo $_POST['closingdate3']; ?>");
        }

        RETaxPaidThru.setMonth(11); //Month is base 0, so DEC = 11 !
        RETaxPaidThru.setDate(31);
        RETaxPaidThru.setFullYear(RETaxYearPaidThru);

        // The number of milliseconds in one day
        var ONE_DAY = 1000 * 60 * 60 * 24;

        // Convert both dates to milliseconds
        var RETaxPaidThru_ms = RETaxPaidThru.getTime();
        var ClosingDate_ms = ClosingDate.getTime();

        // Calculate the difference in milliseconds
        var difference_ms = Math.abs(RETaxPaidThru_ms - ClosingDate_ms);

        // Convert back to days and return
        return Math.round(difference_ms / ONE_DAY);

    }
</script>

Open in new window

0
swendellAuthor Commented:
I tried that first, did not work
I don't understand scope
Image-14.png
0
Michael VasilevskySolutions ArchitectCommented:
If you set initialize the variable with something is it still undeclared at runtime? E.g.

var RETaxYearPaidThru = “1999”;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Olaf DoschkeSoftware DeveloperCommented:
As Michael already said, code that doesn't parse is not something you can ignore. When I said users don't see error messages, that doen't mean it doesn't matter. Suppression of error is just done "in the hope" the JS isn't important.

Besides: If the case is unimportant for a non-existant POST variable, you could also skip the whole else-if-branch in JS instead of writing out invalid JS.

Bye, Olaf.
0
swendellAuthor Commented:
1) I don't actually understand why initializing the VAR with a value like:
var RETaxYearPaidThru = "2015";
corrected this error / scenario but it did.
2) Both Olaf & Michael did help by pointing out JS will check for errors when the page loads. These errors appear when debugging but may not appear to user.
3) When code loads; it is possible for some items to not yet have values.  As a better practice I have all my php return a value from my database when no records are returned. This value will avoid the error I encountered when assigning a JS VAR to nothing and helps me process that scenario better.
4) Michael, I did change my variables to only declare the variable once, helpful.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.