Adding ajax pagination

this whole block should go in above code with just one check inside for loop. This is duplicated code