Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / PHP Tutorial / PHP Advance / How to retrieve data from database in PHP using AJAX?

How to retrieve data from database in PHP using AJAX?

April 28, 2015 by Belal Khan 33 Comments

Hello friends, In the last post we have inserted values to our without refreshing our page. In this post we will learn how to retrieve data from database in php using ajax jquery method. We will fetch data from database without refreshing the webpage. So lets begin but before if you haven’t read the last post you can read it from here.

How to insert values to database in PHP using AJAX?

How to retrieve data from database in PHP using AJAX

Before going through the tutorial you can download the source code from the link given below.

[download id=”1404″]

Creating Database Table

  • First create a table inside your database. I have created a simple table named products as you can see in the below image.
how to retrieve data from database in php using ajax

Database Table

  • You also need to insert some values in your table as you can see above.

Creating HTML Page

  • Now we will create a simple html page with two dropdowns. In first dropdown we will see the brand list. When we change the brand list the other drop down will be loaded automatically by fetching the value from database.
  • You can use the following html code to create your page. Copy and save it as index.html in your project folder.

index.html
XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
 
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='brand'>
<option value='nokia'>nokia</option>
<option value='motorola'>motorola</option>
<option value='samsung'>samsung</option>
</select>
<select id='item'>
</select>
<script src='fetch.js'></script>
</body>
</html>

Creating PHP Script

  • Create a new php file named fetch.php in your project folder.
  • Copy the following code.

fetch.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','myDatabase');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$brand = $_GET['brand'];
$sql = "select item from products where brand='$brand'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('item'=>$row[0]));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>

  • The above code is very simple. We are pushing all the records to an array. Finally we are displaying that array in json format. We will read this JSON using jQuery.

Finally Creating jQuery Script to Make it Work

  • Now we need execute our script using jQuery to get the JSON data.
  • We will change function in our select element. Use the following code

fetch.js
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
$('#brand').change(function(){
$.getJSON(
'fetch.php',
'brand='+$('#brand').val(),
function(result){
$('#item').empty();
$.each(result.result, function(){
$('#item').append('<option>'+this['item']+'</option>');
});
}
);
});

  • Copy and save the above code as fetch.js
  • And include the script to your html page.
  • Try executing your project now.

So thats it for this post about how to retrieve data from database in PHP using AJAX. If you had any confusion in my code or trouble in following the steps feel free to ask by your comments. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: PHP Advance, PHP Tutorial Tagged With: how to retrieve data from database in php using ajax, php mysql jquery ajax, retrieve data from database using jquery ajax

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Vinay Singh says

    April 30, 2015 at 7:05 am

    excellent keep it up

    Reply
    • Belal Khan says

      May 1, 2015 at 3:20 am

      Thank you sir 🙂

      Reply
  2. caleb says

    July 8, 2015 at 10:43 pm

    That’s very good a post you have there, what if I want to pull more than one data from the database table?

    Can this run simultaneously with another Ajax post, I mean like in a comment box where comments goes into the db when submitted and gets retrieved almost immediately?

    Reply
  3. imran says

    September 9, 2015 at 5:50 am

    plz tell me how to get data into tables whoud u like to make tutorial on it

    Reply
    • Belal Khan says

      September 9, 2015 at 5:51 am

      post your exact question to ask us corner.. you can see the button at the top of right sidebar

      Reply
  4. anitha says

    September 23, 2015 at 10:09 am

    the code which you have been posted is really good but i want the second data displayed in input field instead of select option. i have tried to change to input but it is not working please help me in ths

    Reply
    • Belal Khan says

      September 23, 2015 at 10:14 am

      to display the data in input field you can use the val function of jQuery $(‘your input filed’).val(‘your value’);

      Reply
      • anitha says

        September 23, 2015 at 10:22 am

        thank you sooo much

        Reply
      • anitha says

        September 23, 2015 at 10:23 am

        i have completed bca and m into designing part now started with php development can you help me for the doubts i have

        Reply
        • Belal Khan says

          September 23, 2015 at 12:44 pm

          Yeahh you can connect with me on facebook

          Reply
          • anitha says

            September 23, 2015 at 1:33 pm

            thank you so much can u share me your facebook id

          • Belal Khan says

            September 23, 2015 at 1:42 pm

            http://www.facebook.com/probelalkhan

  5. anu says

    September 24, 2015 at 6:48 am

    hi sir, pls help in php development.
    There are two tables in one database, in both the table one field name is common. In table1 inserting data (name) will not take repeated and in table2 inserting data (name) will be repeated as how many times we r inserting. Now if i’m inserting data in table2 field contains name, price, size. Automatically price should get added in table1 also but by checking name i.e, table2 name should be same as table1 name. And if the price value is 0 in table1 of name(xzy), when inserting data(price as 100) in table2 by checking name(xzy) in table1 price will get changed to 100 and same when inserting data(price as 200) in table2 by checking name(xzy) in table1 price will get changed to 300.

    Please help to do this functionality using php, mysql and javascript

    Reply
    • Belal Khan says

      September 24, 2015 at 6:51 am

      meet me on facebook http://www.facebook.com/probelalkhan

      Reply
  6. edmond ochola says

    October 5, 2015 at 6:26 pm

    You people are true to your code

    Reply
    • Belal Khan says

      October 6, 2015 at 1:37 pm

      Thank You Edmond 🙂

      Reply
  7. Marco says

    October 7, 2015 at 8:33 pm

    Hi Belal,

    How would you fit this code to this concept: I would like data to be automatically displayed in a textview twhen the page is opened, therefore rather through a onCreate than onClick?

    Thanks in advance!

    Reply
    • Belal Khan says

      October 8, 2015 at 2:24 am

      instead using click function you can do the task inside ready function..

      $(document).ready(function(){
      //Do the required thing here
      });

      Reply
  8. kamlesh kanani says

    November 6, 2015 at 7:24 am

    hello sir

    i currently working online examination project, i have some project related issue.

    when i add questions and options, right ans value 1 is store on top in database. how to store right ans value.

    Reply
  9. Nemat Tauhid says

    November 27, 2015 at 7:54 am

    Hi Sir,

    I want to insert the data in database which page is already displaying through onLoad() function. when I submit the data and clicking the save button that is inserting in database but that page is going on another page.
    Example:– I have displayed the save.php through onload() profile.php page. after displaying save.php page that is working for insetion in database but that page will go on save.php but I want to hold on profile.php. I have no idea how to do.

    please help me.

    Thanks

    Reply
    • Belal Khan says

      November 27, 2015 at 12:37 pm

      Check this tutorial
      https://www.simplifiedcoding.net/php-mysql-insert-into-database-tutorial/

      Reply
  10. roopesh says

    November 28, 2015 at 8:39 am

    Hello, i need your help for php code, 3 drop down menu- 1st drop down = state, 2nd drop down=district, 3rd drop down= city/town, please tell me how to work with mysql one database and one table, using ajax loader.

    Reply
    • Belal Khan says

      November 28, 2015 at 12:47 pm

      Tell me how far you have done?

      Reply
      • roopesh says

        November 30, 2015 at 6:08 am

        <option value="”>

        Reply
        • roopesh says

          November 30, 2015 at 6:17 am

          Select Blood Group *

          Select Blood Group
          A+
          A-
          B+
          B-
          O+
          O-
          AB+
          AB-
          A1+
          A1-
          A2+
          A2-
          A1B+
          A1B-
          A2B+
          A2B-

          Select State *

          Select State
          ANDAMAN & NICOBAR ISLANDS
          ANDHRA PRADESH
          ARUNACHAL PRADESH
          ASSAM
          BIHAR
          CHANDIGARH
          CHATTISGARH
          DADRA & NAGAR HAVELI
          DAMAN & DIU
          DELHI
          GOA
          GUJARAT
          HARYANA
          HIMACHAL PRADESH
          JAMMU & KASHMIR
          JHARKHAND
          KARNATAKA
          KERALA
          LAKSHADWEEP
          MADHYA PRADESH
          MAHARASHTRA
          MANIPUR
          MEGHALAYA
          MIZORAM
          NAGALAND
          ODISHA
          PONDICHERRY
          PUNJAB
          RAJASTHAN
          SIKKIM
          TAMIL NADU
          TELANGANA
          TRIPURA
          UTTAR PRADESH
          UTTARAKHAND
          WEST BENGAL

          Select District *

          Select District

          Select Location *

          Select City / Town

          1st option= blood group
          2nd option=state (mysql database table contrypincode, data same)
          3rd option=district( 2nd option select, onchange 3rd option)
          4th option=city(3rd option select, onchange 4th option)

          batabase(contrypincode-table)
          id,
          statename,
          districtname,
          citytown

          Reply
  11. shahrukh says

    May 19, 2016 at 11:08 am

    hiiiiiiiiii bilal contact me

    Reply
  12. prem says

    May 24, 2016 at 4:29 pm

    hello

    i want to do same function on radio button

    can u define it?

    Reply
  13. Mayuresh K says

    June 7, 2016 at 11:03 am

    please help to solve this.. I have one form with 4 input tag and 2 buttons Save and Edit And One grid in that i fetch data from database. But Now i Want when i click any one row from grid i want click event to go in database and fetch data and fill all field present on form but that not working for me, i havn’t got one solution please help me

    Reply
  14. Deepak Singh says

    November 17, 2016 at 11:50 am

    Your Codes are Good But Your Site has Awesome SEO .

    Great Work Guys……

    Reply
  15. Playboy Sanjiv007 says

    November 25, 2016 at 12:40 pm

    i am also a MCA student and always try to keep it simple and less as well as possible.
    it was very easy and accurately coded.

    Thanks dear

    Reply
  16. mary says

    January 27, 2017 at 7:15 am

    Hello. This code is working fine. Thank you. actually i’m working on a project where I’ve to fetch latitude and longitude from a database. Using this code I got an output which has a string of lat long in it. Now i want to split them. can you please help me with this? How should i take the output in a variable? As in your code, $(‘#item’).append displays the result. How to take this result into a variable ?

    Reply
  17. nishil patel says

    February 17, 2017 at 2:00 pm

    i want to fetch data by id from database and show data on update using dialog-box ajax…

    Reply
  18. Hari says

    May 30, 2018 at 11:56 am

    Please help me, i am new to php

    I need to display student registered details one by one in form from database by clicking on next button.
    I created the registeration form and inserted details into database,but i am not aware to view each student details one by one using next button.

    Reply

Leave a Reply to Hari Cancel reply

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

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.