Why does Javascript function run without being called??

swendell
swendell used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Olaf DoschkeSoftware Developer
Commented:
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.
Michael VasilevskySolutions Architect

Commented:
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.

Author

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
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Michael VasilevskySolutions Architect

Commented:
Your code must parse with valid syntax in order for the page to load. Correct all syntax errors before proceeding.

Author

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

Michael VasilevskySolutions Architect

Commented:
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

Author

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

var RETaxYearPaidThru = “1999”;
Olaf DoschkeSoftware Developer

Commented:
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.

Author

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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial