Fetch Data from MYSQL using Jquery Ajax

This is really an interesting article where I will show you how to fetch data from MySQL table using Jquery Ajax. If you are familiar with PHP, then you may already know about how to fetch data using PHP. But in this tutorial, I will show a completely different way of doing this. Ajax is a technology which extracts and displays the web content without loading the full page. I can update a single HTML
without loading the full website. Now, lets move to a step by step procedures for pulling all the data out of MySQL table and displaying in HTML table.

The first thing you need to do is create a simple MySQL database with some tables with some data. You can do this using simple SQL query but I have already a data of population of districts of Nepal in my database. I will use it in this tutorial. If you want to display different data then its ok just create a mysql table and insert some data in it.

Now write a simple PHP code that fetches the data from the table that you created. The PHP code connects to the database, selects the database, read the contents of the table and fetches the table rows. You can store each row in a different array with only those fields you need to display. Here is the code for this [lets say the file name as district.php]

 $row['name'], 
   'pop_male' => $row['pop_male'],
    'pop_female' => $row['pop_female'],
    'pop_total' => $row['pop_total']
   );
  array_push($data, $row_data);
 }

 echo json_encode($data);
?>

Here I made a simple array named $data. I push back each row to that array. And notice at the end of the code I have echoed the JSON encoded data. What this means? This is the most important step actually. I have converted the regular PHP array into JSON (JavaScript Object Notation) format. You can output in XML or JSON format. I like JSON because it is simple and easy for the beginner. The JSON is language independent. It is in name/value pair like Python dictionary or Java map. If I see the above file in browser having Jsonview extension. I will see the following output

It has exactly same attributes as I defined in php file. You can access those fields using simple . operator as you did in C structure or C++ Objects. For example to access the name I will write data.name, similarly for pop_male I will write data.pop_male.Now the next step is writing some Ajax code. I already said that I will use Jquery Ajax. Make a simple file and called it index.html. And write a simple ajax code that reads the above JSON formatted data and put it in the HTML table. The ajax code for this is