Reputation: 1949
I'm getting tired of firebug telling my vars aren't defined...
I have a button: next. When the button is clicked, I want it to load a php page into a div, assigning the php page the variable representing the next page.
To do this, I have a variable crntpage that stores the value of the current page. In order to calculate what the var for the next page must be I have a function called next which calculates the value and returns it.
Let's assume that we are on page 5:
javascript
$(document).ready(function() {
$.ajax({
url: 'pagination.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (pages) {
last = pages['last'];
crntpage = 1;
function nxt(b) {
if (b == last) {
next = last;
} else {
next = b + 1;
}
return next;
}
$('#next').live('click', function() {
crntpage(next);
$('#content').load('getposts.php?pagenum=' + nxt(crntpage));
return false;
});
}
});
});
html
<div id="previous">
<a href=''> <-Previous</a>
</div>
I keep getting an error saying that next isn't defined. My guess is because my nxt function is not receiving the value of last. What am I doing wrong?
Upvotes: 4
Views: 197
Reputation: 3136
What you are trying to do with the nxt
function can be accomplished more idiomatically with Math.min()
:
$('#next').live('click', function() {
crntpage = Math.min(crntpage + 1, last);
$('#content').load('getposts.php?pagenum=' + crntpage);
return false;
});
You should also prefix variable declarations with the var
keyword, so as not to pollute the global namespace.
Here's the revised code together:
$(function() {
var currentPage = 1;
var last = 1;
$('#next').live('click', function() {
currentPage = Math.min(currentPage + 1, last);
$('#content').load('getposts.php?pagenum=' + currentPage);
return false;
});
$.ajax({
url: 'pagination.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (pages) {
last = pages['last'];
}
});
});
Upvotes: 2
Reputation: 12000
It looks like you didn't define next
. (or maybe it is defined in the part of your code that you didn't post here, I don't know) Have you tried this:
$(document).ready(function() {
var next = ''; //defining the variable first, then you set it below in nxt()
$.ajax({
url: 'pagination.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (pages) {
last = pages['last'];
crntpage = 1;
function nxt(b) {
if (b == last) {
next = last;
} else {
next = b + 1;
}
return next;
}
$('#next').live('click', function() {
crntpage(next);
$('#content').load('getposts.php?pagenum=' + nxt(crntpage));
return false;
});
}
});
});
Upvotes: 0