My function will not work?

I'm tired of firebug telling that my vars are not defined ...

I have a button: next. When the button is pressed, I want it to load the php page into a div, assigning the php page a variable representing the next page.

For this, I have a crntpage variable that stores the value of the current page. To calculate what should be for the var variable for the next page, I have a function called next, which calculates the value and returns it.

Suppose 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 the following is undefined. I assume that my nxt function does not get the last value. What am I doing wrong?

+4
source share
2 answers

What you are trying to do with the nxt function can be done 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']; } }); }); 
+2
source

It looks like you did not define next . (or maybe it is defined in part of your code that you did not post here, I do not 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; }); } }); }); 
0
source

Source: https://habr.com/ru/post/1383153/


All Articles