Link to home
Start Free TrialLog in
Avatar of swendell
swendell

asked on

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...User generated image
<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

SOLUTION
Avatar of Olaf Doschke
Olaf Doschke
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Avatar of swendell
swendell

ASKER

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?

User generated image
Your code must parse with valid syntax in order for the page to load. Correct all syntax errors before proceeding.
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
User generated image
 <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

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

I tried that first, did not work
I don't understand scope
User generated image
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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.