Load JSON Data with jQuery and PHP

Must Read : Load JSON Data with jQuery and PHP

While working on a project I was to get records from database and show on some textboxes. I knew that I need to use jQuery to do this, but how can I do this. After somegoogling I find that I can do it very easily with JSON. I just need to fetch recordsfrom database and then convert that records to JSON and then send it to jQuery. Andthrough jQuery we can easily display JSON encode data. In other words, through JSON wecan interchange data between web server and browser.

In this tutorial I’ll show you, how to load JSON data in select (combo) box and how can we put JSON data in textboxes.
Lets suppose we have to fetch data from category table of a database (lets say database name is wearecoders).

We need to create some files for database connections and fetching data from database.

connect.php

You can configure server and database name here.

Now we need to fetch all categories from the database, encode into JSON and then we can put all those categories in the combo box. All we have to do is to create a file json_data_combo.php

json_data_combo.php

when you open json_data_combo.php directly the result will looks like

Now we have to read this file through jQuery and display this json encoded data in the combo

we need to include following jQuery

and here is the complete working code for main file where we will use jQuery and show dropdown list

main.html

Our first task is complete, we have successfully loaded the JSON data into dropdown list through jQuery and PHP. Now, our next task is to show data in text boxes. Now, what we’ll do, select a category from a drop down list and press load button to put selected category name and description in text boxes and textarea. For this purpose we need to create a php file to get category by its id and convert that category data into json and send to jquery to display.

json_data_category.php

Now we need to modify our main.html file so replace the code of main.html with this.

main.html

That’s it. I hope this is really cool one. Thanks for visiting,. Keep in touch with us for more tutorial.