views:

259

answers:

2

I am trying to create a dynamic pagination system for my website and I've decided on using ajax callback function to dynamically show the comments when the user clicks on different page elements.. So I'm pasting the code below as an example as to how I am doing it...I would like to ask you guys if I'm doing it right or if their is any better way to do it please point me to the right direction:

javascript :

$(document).ready(function(){
$(".pages").click(function(){
var pageno=$(this).attr("id").slice(4,8);//slicing out numbers from the id i.e "1" from "page1"
$.get("news.php", { pageno: pageno},
    function(data){
     $("#comments").html(data);
    });
});
});

html:

<div>
<span id="page1" class="pages" >1</span>
<span id="page2" class="pages" >2</span>
<span id="page3" class="pages" >3</span>
</div >
<div id="comments">
</div>

php:

<div><?php echo $_REQUEST['pageno'];?></div>
+1  A: 

I don't think this is unreasonable, though I'd mention two thoughts.

First, I think it is a good thing to assign the click handlers dynamically rather than actually putting "click=" into the HTML (this is the heart of "progressive enhancement"). Hoerver, you may want to use a different type of selector. Finding a group of elements by class is one of the slower ways to define elements, especially if there may be many pages. You could put them all within a div and do $("#myDiv span").click(). That should be much faster.

Second, making the assumption that the page number will always start at the fourth character of the span id seems a bit fragile. It might be better to just make the id be the page number by itself.

JacobM
Thanks I will take that as an approval of what I am doing and I will take your suggestion to make the id be the page number by itself..... thanks a lot....Are their any errors handlers that I should add?
halocursed
and I was using "page1" instead of "1" because acc. to W3c standards you shouldn't name your id's starting with numbers.....
halocursed
+1  A: 
$(document).ready(function(){
    var isWorking = false;
    $(".pages").click(function(){
     if ( isWorking ) 
     {
      alert('Please wait for your preceeding request to finish.');
      return false;
     }
     isWorking = true;
     var pageno = $(this).text();
     $.get("news.php", { pageno: pageno},
      function(data){
       $("#comments").html(data);
       isWorking = false;
      });
    });
});
  1. It looks like you could simply use the text content of the span for the page number (see the .text() change).

  2. You might want to prevent users from trying to load too many pages at once (see the isWorking variable, which should prevent users from loading more than 1 page at a time).

ken
Thanks I will look into all your suggestions...Are their any errors handlers that I should add?
halocursed