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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With