Using Ajax and PHP to get content from a database

May 28th, 2012

Up until now I’d only used Ajax to send information to a PHP file to send an email or to enter something into a database. But last week I started working on a site that featured pop ups that would contain some information from a database. Should have been easy to figure out right? Well, it’s pretty simple after you know what to do but there I ran into one problem, almost every example I came across was written by a PHP developer so they all focused on the JavaScript side.

In the demo I’ve made, there isn’t any database queries, it’s mainly just an example to show everything working. But they’ll be in the code in this post in case you you’re unsure how to do that.

First, we’ll look at the JavaScript. I’m using jQuery because it makes like a lot easier. If you haven’t used Ajax for anything before, this is usually what I would write in order to enter something into a database:

1
2
3
4
5
6
7
8
$.ajax({
    type: ‘POST’,
    url: ‘file.php,
    data: dataString,
    success: function() {
        // code to run when the info is sent succesfully
    }
});

This shouldn’t be too hard to understand even if you’ve never work with Ajax before. The type is POST which is the same as when you have a form and you write method=”post”. The url is the php file we want to send the data to and the data is the obviously what we want to send. And finally, success is what we want to do after we’ve sent the data and it was successfully received. This is good if we’re just going to send something but how to we get content and display it? Well, luckily for us, jQuery will take care of a lot of the work for us. To get content back, all we need to do is add this:

1
2
3
4
5
6
7
8
9
$.ajax({
    type: ‘POST’,
    url: ‘file.php,
    data: dataString,
    success: function(html) {
        console.log(html);
        // code to run when the info is sent succesfully
    }
});

We passed a variable to the success function, I’ve just called it html because that’s what we’ll be passing to it, but it can be called anything. That was pretty easy, in fact all you really need to worry about is the url to your php file and what you’re passing it. Now on to the part that gave me some trouble, how do we get our content and pass it back to the success function. Guess what, this will work just fine:

1
2
3
<?php
    echo “This is some content”;
?>

If you ran this, you would get “This is some content” logged out. Ok, so how about a real world example? I wanted to get some content from a database and put it in a pop up. Here’s the relevant code that I used. First, I used php to get to some some links out of my database:

1
2
3
4
5
6
7
8
<div class=”links”>
<?php
   while ($row = mysql_fetch_array($result)) {
       echo “<p>”.$row[‘title’].”</p.”;
       echo “<a href=’#”.$row[id].”’>Link</a>”;
    }
?>
</div>

What we would get here is the title field on our table and the id field would be added to the hash mark of the link. This way we can use that to get the right content from our database. Now on to the jQuery.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var body = $(‘body’);
var links = $(‘links a’);
var content = $(<div class=”content”></div>);

links.on(‘click’, function(e) {
    e.preventDefault();
    var hash = this.hash.replace(‘#’,’’);
    var dataString = ‘id=+ hash;
    $.ajax({
        type: ‘POST’,
        url: ‘file.php,
        data: dataString,
        success: function(html) {
            body.append(content);
            content.html(‘’);
            content.append(html);
        }
    });
});

When we click on one of the anchor tags in the links div, we get hash and remove the hash mark leaving us with just the number. We then pass that number as the id to our php file. Finally, we take the content that’s returned and append it to our body tag. If you’re not that familiar with jQuery,

1
var content = $(<div class=”content”></div>')

will create a div with the class of content for us. Now our php:

1
2
3
4
5
6
7
8
9
10
11
<?php
    if (isset($_POST['id'])) {
        $id = $_POST['id'];
    }
    $query = “SELECT * FROM table where id =$id’”;
    $result = mysql_query($query, $link);
    while ($row = mysql_fetch_array($result)) {
        echo<h3>.$row[‘title’].</p>;
        echo<p>.$row[‘content’]/</p>;
    }
?>

There we go, now it will grab the title and content from our fictitious database and the resulting HTML will be added to our pop up. Remember, my demo doesn’t have any of the database queries, it just shows the functionality of the code, but you’ll just need to create a database connection and add the php from this post to make it all work.

This won’t work if the user has JavaScript turned off but if the client is ok with this, then it’s not really a big deal and really, who has JavaScript turned off anymore? Pretty simple and the great thing is there’s not page reloading which makes the experience for your visitors a whole lot smoother.

Leave a Reply

Your email address will not be published. Required fields are marked *