How to populate a select box using jQuery ajax json, php?





Hello Friends! With the help of Ajax and PHP you can easily populate a select box without refreshing the page. You can also do it using only PHP script but requires you to refresh the page every time you change the select box value. Here is a very simple and useful example how you can populate a select box without refreshing page.

Prerequisites

1. Latest version of JQuery.

2. Very basis understanding of JSON.

3. A server side scripting knowledge to respond to Ajax request. In this tutorial I am going to use PHP as a scripting language.

Code:

There are 4 parts in this DEMO.

HTML page

The JQuery & Ajax (Client side code)

JSON structure

Server side code to populate dynamic page.

HTML:


  <select id="category">

      <option value=""> Select Job Type</option>

      <option value="1">Technical </option>

      <option value="2"> QA </option>

  </select>

 <select id="sub-category">

      <option value=""> Select Area Lead</option>

  </select>


JQUERY & AJAX REQUEST:

Include latest version of Jquery in your HTML page. Below ajax script will call server side script to get JSON data and populate select box. Add below script in your page.

 


$(function(){ 
    $('#category').change(function() {
        
        $.ajax({
            type: "POST",
            url: 'https://appsntechinfo.com/demo/list_ajax',
            data: {'categoryID': $(this).val(),'isAjax':true},
            dataType:'json',
            success: function(data) {

               var select = $("#sub-category"), options = '';
               select.empty();

               for(var i=0;i<data.length; i++) {
                 options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";              
               }

               select.append(options);
            }
        });
    });
});


And now in your server side page you may write below to fetch data from database.

SERVER SIDE SCRIPT:

We will first validate the category id and fetch data from database then return JSON response to UI.

 

if (isset($_POST['categoryID'])) {

    $id = trim($_POST['categoryID']);
    $result = array();
    $id = mysql_real_escape_string($id);
    $res = mysql_query("SELECT * FROM sub_categories WHERE category_id = $id");
    while ($row = mysql_fetch_array($res)) {

    $result[] = array(
      'id' => $row['subcatid'],
      'name' => $row['description']
    );

    }

    echo json_encode($result);
}

SAMPLE JSON:

 

[
  {"id":10, "name": "Anderson"},
  {"id":11, "name": "Shane"},
  {"id":12, "name": "Shelly"}
]

2 comments:

  1. Thanks a loto for this script! It was what I' was looking for!

    ReplyDelete
    Replies
    1. Most welcome Maria..... Keep visiting for new posts here....

      Delete

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved.