Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript does not take an account of the conditions exit, while variables are nevertheless equal to the output condition

I have a HTML form that submit to a JavaScript, the data is processed and a POST request is sent to a PHP script.

var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if(contentElt && xmlHttp.responseText) {
                    var ajaxData = JSON.parse(xmlHttp.responseText);
                    var processedResultCount = parseInt(ajaxData[0]);
                    totalResultCount += processedResultCount;

                    contentElt.innerHTML = "Date processed (month - year): " + recupMonth + " - " + recupYear + "<br/>Results processed: " + processedResultCount + "<br/>Total results processed: " + totalResultCount;

                    pageNum++;
                    writeMode = "a";

                    if(processedResultCount === 0) {
                        pageNum = 1;
                        recupMonth--;
                        if(recupMonth === 0 && recupYear > endYear) {
                            recupMonth = 12;
                            recupYear--;
                        }
                        else if(recupMonth === endMonth && recupYear === endYear) {
                            alert("Processing finished");
                            if(totalResultCount != 0) {
                                contentElt.innerHTML = "Total processed results: " + totalResultCount + '<br/><br/>&gt; <a href="amazon_keyword_stats.csv" title="Download CSV result file">Download CSV result file</a>';
                            }
                            return;
                        }
                    }

when I arrive at the condition

else if(recupMonth === endMonth && recupYear === endYear)

and the condition are satisfied. Code doesn't go in.

continues to decrement the month and when it gets to -2, it still performs five iteration and then the code arette not offer a CSV download.

I do not understand why it happens like that, someone would have a clue?

like image 576
mortiped Avatar asked Nov 01 '22 11:11

mortiped


1 Answers

else if(recupMonth === endMonth && recupYear === endYear)

Are recupMonth, endMonth, recupYear and endYear the same type? Because may be some of them are strings instead of numbers and the operator "===" is not treating them as equals.

If you are not sure, you can try by parsing them to numbers inside that condition (at least to try if that works):

else if(parseInt(recupMonth, 10) === parseInt(endMonth, 10) && parseInt(recupYear, 10) === parseInt(endYear, 10))

Or trying by not comparing types too:

else if(recupMonth == endMonth && recupYear == endYear)

Hope this helps.

Regards.

like image 115
Mindastic Avatar answered Nov 15 '22 04:11

Mindastic