Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var becomes NaN after incement by 10 in function

Tags:

javascript

var post = 10;
function load_more(str) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("add").innerHTML = document.getElementById("add").innerHTML + xmlhttp.responseText;
            }
        };
        var post = post + 10;
        xmlhttp.open("GET", "fetch_more.php?number=" + post , true);
        xmlhttp.send();
}

When i load the website i expect the browser to define the value 10 to post and do nothing more until i press a button that calls the load_more() function which increments that value by 10 and passes it to the PHP via Ajax.

The desired behaveiour is to have 10 post on the site and then load 10 more on button press each time the button is pressed.

But PHP just throws an MySQL error and the log shows that the post var is NaN.

like image 439
Gala Avatar asked Feb 09 '23 03:02

Gala


1 Answers

The line

var post = post + 10;

is the culprit here. Javascript has a behaviour called hoisting, which essentially means that your variables are always declared at the top of the scope.

So in your code, what happens is the following:

var post = 10;
function load_more(str) {
    var post; // `post` is now undefined
    //...other code
    post = post + 10; // undefined + 10 evaluates to NaN
}

I hope you can see that since post is re-defined at the beginning of the function, post is undefined when you use it in post + 10, which causes post = post + 10 to evaluate to NaN (since undefined + 10 evaluates to NaN).

To solve your problem, just remove var from the front:

post = post + 10;

or:

post += 10;
like image 97
Oskar Avatar answered Feb 16 '23 04:02

Oskar