November 4, 2011 jquery

Display database information with ajax, jQuery and PHP.

Display database information with ajax, jQuery and PHP.

As the topic mentions, we will be creating a simple button, that once it is clicked, it will call a PHP script, look inside the database for information, and return to the browser, without refreshing or leaving the page. I have decided to write this post, thanks to a fellow mate in PHPFreaks forum. He needed help with this same situation, and I helped him out. Let me remind you, this example is made very simple. This intentionally made this way to be able to understand this exercise, and afterwards, use this same code for any of your projects or needs. Hope you enjoy.

First, lets create the button, and the div that will contain the ending result.

Notice that we are using the jQuery library for this. This library can be included through google libraries like the code above, or you can download it and have it in your server and have the ‘src’ path point to your file. We have named the button with an id – getdata. We have also named the div that will contain the result with id – result_table. These are needed for the jQuery to work well.

Quick Tip: You should get the habit of having a good naming convention, for example, our div result_table has that name because we will show the results from the database table. You will love yourself for doing this in the future, since you might be the one maintaining the code, and if it’s not you, then the next coder will love you for doing so.

Let’s add the javascript with jQuery to handle what happens when the button is clicked. Let’s add the following script under the div:

How ajax works

When you see this:

This means that we want to bind the ‘click’ event to this button. In there, we see a function. This is a function that will execute inside the click event. Since this is a very simple example, we go directly to the ajax. As you noticed, the ajax is refered to $.ajax(); Ajax stands for: asynchronous javascript and xml. Ajax is a powerful tool that can be used to send and retrieve data from the server without having to refresh the page. So in other words, here’s what happens,

An event happens: Click a button.
Request is sent to your server: send data from an input or something(it’s optional).

Server picks up your request
Server process your request
Server sends back a result.

Once the server is done, the browser picks up the result, usually an object. After receiving the result, you can manipulate with javascript, what you have on the page. In order to achieve this, we would define some values such as, url, type datatype. Once we receive the result, we would place a function in the success definition. This means, that what ever is inside, will be executed on the return from the server. In this case, we have {php}$(“#result_table”).html(output_string);{/php}, meaning that the result coming from the server will replace whatever we have in that div at the moment.

The PHP script

In the ajax call, we defined the url parameter as: getdata.php. This is the php file that contains what we need to do. Let’s create it.

The include(“connect.php”) file contains our credentials to be able to connect to the database table. I have not made this file, assuming you have an understanding of this already. If not, soon I will post a new example concerning this connection. All we do in the previous file is get connected to the database, retrieve the data, and place it inside a variable, and send it back to the browser. On the PHP script, you see a string concatenation ‘ .= ‘. Once all results are placed in the string, we close the database connection, and send back the string as a json object. That’s why you see, {php}echo json_encode();{/php}. The final resulting html page should look like this.

This script is ready to be executed, and deliver what we need.

22 thoughts on “Display database information with ajax, jQuery and PHP.

    1. I use the same code and had a problem at first while clicking the button so I change the single codes of getdata.php into double code then it worked for me.

    1. You can define a variable with the data like this:

      And in the ajax call, just add an attribute “data”, like this:

  1. thank you for sharing your knowledge mr.. Jotorres.
    this really helped me,

    i have object data array from checkbox and how i send value form array checkbox with ajax

    this my code

    …..

    Delete Data.

    ……

    function get_data(nil,fol,dari=”){
    var datahp = document.getElementsByName(‘piltask[]’);
    var post_data = datahp.value;
    …….ajax
    }

    and….. not work 🙂
    can you help me mr Jotorres, what is wrong in my code

    thx ms Jotorres
    God bless you

  2. Hola su script me ha parecido muy útil en mi caso estoy integrándolo a wordpress como parte de una plantilla pero no me funciona nada cuando pincho en botón, sería tan amable de ayudarme? Este es el código que escribo en la página php para mi plantilla:

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

    $.ajax({
    url: ‘executeDateQuery.php’,
    type:’POST’,
    dataType: ‘json’,
    success: function(output_string){
    $(‘#result_table’).append(output_string);
    } // End of success function of ajax form
    }); // End of ajax call

    });

    El fichero executeDateQuery.php lo he incluido en la misma carpeta de la plantilla wordpress. Muchas gracias por su atención

  3. Disculpe no puse el código completo, como le decía cuando hago click en el botón no sucede nada, esta sí es la versión completa:

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

    $.ajax({
    url: ‘executeDateQuery.php’,
    type:’POST’,
    dataType: ‘json’,
    success: function(output_string){
    $(‘#result_table’).append(output_string);
    } // End of success function of ajax form
    }); // End of ajax call

    });

  4. This is a great tutorial, but wondered if slightly changing it so that rather than clicking the checkboxes and then selecting the button at the end, can be changed so that the search happens as soon as the checkbox is clicked, so the results change each time tou select the checkbox.

    Great though, cheers

Leave a Reply

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

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.