Use AJAX with checkboxes to filter content from database

Greetings everyone,

I’m using checkboxes to filter content retrieved from a MySQL database. To avoid page reloads, I’d like to try this with AJAX but I’m not sure where to begin. Would it be easiest to use jQuery to handle the AJAX requests and whatnot?

Thank you in advance!

You can use Jquery ^^; It’s very easy to use, a simple ajax request can look like this:


$.ajax({
    url: 'mypage.php',
    type: 'GET',
    data: {
        somevalue : 1,
    },
    success: function(msg) {
           $('#content').html(msg);
    }
});

For more info, try looking at the Jquery website:

http://api.jquery.com/jQuery.ajax/

Hey RedBishop, how you doing?

If you’re already using jQuery on your site, then it makes sense to use it to make your AJAX requests. If you don’t, then it’s better to include a smaller AJAX helper library (check this post) - it’s not worth loading jQuery if you don’t need most of the functionality.

Hi Patche,

thank you for the info!

Hey fretburner,

I’m good thanks. Hope you’re doing well. I’m happy to report that my PHP skills are ‘steadily’ improving, from terrible to mediocre, so at least there has been some improvement :wink:

I am already using jQuery on my site, although not on that particular page with the checkboxes. Perhaps a smaller AJAX helper library would be a better option as you suggested. Hopefully you can help me out when I run into difficulties with the AJAX code!

Yeah, I’m doing well thanks :slight_smile:

If you’re already including jQuery on other pages of your site, you might as well stick with that… your users will have it cached, so there won’t be any additional overhead.

OK, I’m back already.

Stupid question no1:

Lets say that I have a PHP pagination script. Do I need to rewrite this script in JavaScript for the purpose of using AJAX?

My pagination links are contained between paragraph tags, so I’ve given the <p> tag an id. The id is then assigned a click handler in my JavaScript file.

$(‘#ajaxpagi’).click(function() {

Am I on the right track?

Thank you!!

If you’re already including jQuery on other pages of your site, you might as well stick with that… your users will have it cached, so there won’t be any additional overhead.

@fretburner - that makes sense, thanks.

Instead of manually submitting a form with your pagination variables and filter options, you just make your request via ajax, passing the variables. Your PHP script will need to be altered to detect if the request comes in via AJAX (see this link), and return only the search results section of the page, which you can then swap with the previous results.

Instead of manually submitting a form with your pagination variables and filter options, you just make your request via ajax, passing the variables. Your PHP script will need to be altered to detect if the request comes in via AJAX (see this link), and return only the search results section of the page, which you can then swap with the previous results.

Hi fretburner,

if only it were that easy…

What variables would need to be passed to the JavaScript file? The pagination script includes a number of variables, most of which are used in “if else” statements. Must I pass all of the variables? Don’t I need code in my JavaScript file that is similar to that used in the PHP script, otherwise how would the passed variables be manipulated? There must be some context, which is why I asked about rewriting the PHP script. :confused:

Thank you for your help.

Could you share an example page, showing the pagination controls etc that you already have in place (that currently work without JS)? It will be easier to give you advice if I can see what you’re working with.

Hi fretburner,

thanks for getting back to me.

I cannot post all of the code, but this is a snippet of how it looks like.

	if ($current_page != 1) {
		echo '<a href="page1.php?startingitem=' . ($start- $itemsperpage) . '&pages=' . $pages . '">Previous</a> ';

All of the numbered pagination links and previous/next links include parameters on the end of the URLs. Don’t know if this is enough information!

I did some googling and came across this on Stackoverflow. http://stackoverflow.com/questions/15148728/how-do-i-implement-ajax-jquery-to-an-existing-php-mysql-pagination-script

There is a post that uses the jQuery .load() function with a pagination script. Is this something that you would recommend?

Thank you.

Yes, the first part of the answer is pretty much how I’d recommend you do it. The other way (the second half of the answer) is more efficient, but it’s also a little more complicated to implement.

You want your JS to attach an onclick handler to each of your pagination links, to prevent the link from being followed and instead make the request (using the same url) via AJAX (the code from the Stack Overflow answer is very similar to what you’ll need). Your PHP script should detect the AJAX request (using the code I linked to previously) and instead of sending back the complete page, only send back the section with the new results, which your JS can insert back into the original page.

If you get stuck with either part (JS or PHP), let me know.

I will try and see what I can come up with. Thanks again for all of your assistance :slight_smile:

Cheers for now.

Ahoy fretburner!

I’m sorry to do this but I must bug you or someone else again.

This Ajax pagination script isn’t working yet. I’ve tried the .load() method, however some things aren’t clear to me. As you will see the Javascript code is not complete.

OK, from the code I’m selecting the content with an ID of ‘pagination-links’. Then we’ve got some more code, then retrieve the href attribute of the current anchor, which is used in the load method. The load method then loads the current URL’s content into the specified selection.

The href attribute will be mypage.php with a few name/value pairs attached to the end of the URL. This is only the href attribute so I still need the open/close tags and the content (pagination numbers, previous, next text) between the tags to load the desired content.

If you have some time, could you please assist me with this? I hope this makes sense and I apologize if I’m not expressing myself better.

Thanks a lot!

<script type="text/javascript">

$(function(){

    $('#pagination-links').on('click', 'a', function(e){

        e.preventDefault();
        var $this = $(this);
        var url = $this.attr('href');
   $('#paginated-content').load(url){

	


        });

});
});	
 </script>

The content that I’m retrieving from the database is contained in a div with an id of ‘paginated-content’.

<div id="paginated-content">
<div>record1</div>
<div>record2</div>
</div>

The links:

<p id="pagination-links">1
<a href="mypage.php">2</a>
<a href="mypage.php">3</a>
<a href="mypage.php">4</a>
</p>

Hey RedBishop,

Your code looks OK except for this line, which should be:

$('#paginated-content').load(url);

Also, shouldn’t your links have a query string appended like you showed in a previous post? Something like:


<a href="mypage.php?startingitem=11&pages=2">2</a>

Hi fretburner,

thank you for getting back to me. I would have replied sooner but I first wanted to get the script working. Needless to say it doesn’t work. I’ve tried various things, but nothing seems to work. If I click a link nothing happens.

I have posted my code below, but have left out the parts that create the actual pagination – not sure if I’m “allowed” to post the code. Just to be clear what my code is supposed to do: The content in the div with id “paginated-content” is placed in the div with id “container” when a link is clicked. I’m uncertain if the current content in “paginated-content” must be removed before the new content is added.

Perhaps you can see at a glance what the problem could be. I’ve spent a few hours on this and have gotten nowhere.

Thanks for your time and help.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test ajax</title>	
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>	
<script type="text/javascript">
$(function(){

    $('#pagination-links').on('click', 'a', function(e){

        e.preventDefault();
        var $this = $(this);
        var url = $this.attr('href');
	$('#container').load(url + '#paginated-content');
});
});	
</script>
</head>

<body>

```php
&lt;?php		
echo '&lt;div id="container"&gt;
&lt;div id="paginated-content"&gt;';

// query begins here:
$q=...
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
// records from database here
}

echo'&lt;/div&gt;
&lt;/div&gt;';

//pagination links begin here:
echo '&lt;div id="pagination-links"&gt;';
// all links here
echo '&lt;/div&gt;';
	
?&gt;
```

Do you mean allowed by Sitepoint? Because there’s no problem with posting your code here… if you’re worried about it being too long, you could either zip it and attach it to your post, or add the relevant sections of code to a gist. Alternatively, seeing it running online somewhere would be quite helpful, if you have a link.

No, this pertains to copyright issues. I need to find out if the code I’m using can be posted on the Internet.

Thanks!

Hi fretburner,

are you still around?

Sorry to drag this up again, but I’m still having some trouble using Ajax with my pagination links.
Been doing some other stuff in the mean time.

This is the closest I could get to them working with the load method:

$('.pagination-links').load(encodeURI(url) +'a .pagination-links');

<p class="pagination-links">1
<a href="mypage.php">2</a>
<a href="mypage.php">3</a>
<a href="mypage.php">4</a>
</p>

However, what happens is that two sets of pagination links appear on screen, instead of one.

Could you please help me with this? Thanks a million.

Hey RedBishop, how you doing?

Yeah, I’m still here… you don’t think I’d miss out on the move to Discourse do you? :wink: What do you think to the new forums?

That last piece of code you posted is a bit confusing… it looks like you’re trying to load in content to the p.pagination-links tag? Do you have a link where I could see the code in action?

Hey fretburner,

please excuse my late reply! I’m doing well thanks, and you?

I like, I like, though I haven’t been online that much.

It’s okay, I’m going to try another technique. Can I get back to you if I’m still stuck?

Thanks, keep well.