FOLLOW

Thursday, January 18, 2018

How To Populate JSON Data In Select Dropdown Using jQuery?

ViewUserData.php


<?php

$DatabaseServer = "localhost";

$DatabaseUsername = "root";

$DatabasePassword = "root";

$DatabaseName = "demo";


$Connection = mysqli_connect($DatabaseServer , $DatabaseUsername ,  $DatabasePassword , $DatabaseName);

 

if($Connection=== false){

    die("ERROR: Could not connect. " . mysqli_connect_error());

}


$SQL = mysqli_query($Connection, "SELECT * FROM User");

$Result = array();


while($Row = mysqli_fetch_assoc($SQL))    {

       $Result[] = array(

          'FirstName' => $Row['FirstName']            

       );

    }


    echo  json_encode($Result);

?>


Output:

JSON Array:



[{"UserID":"1","FirstName":"Ram","LastName":"Sri"}]


ViewUserData.html


<Html>

<head>

<script language="JavaScript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>

$(document).ready (function () {

            $.getJSON ("ViewUserData.php",

                function (json) {

                    for (var i = 0; i < json.length; i++) {

                        $("#UserID").append("<option>" + json[i].FirstName+ "</option>");

                    }

                });

});

</script>

</head>


<body>


<select id='UserID'>

//Your Json Array comes here
</select>


</body>


</html>


Output:










MySQL: Run these two queries


CREATE TABLE `user` (
  `UserID` int(12) NOT NULL,
  `FirstName` varchar(48) NOT NULL,
  `LastName` varchar(48) NOT NULL,
  `Email` varchar(128) NOT NULL,
  `City` varchar(48) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `City`) VALUES
(1, 'Ram', 'Sri', 'zzz@zzz.com', 'Delhi'),
(2, 'Krishna', 'Vasudev', 'yyy@yyy.com', 'Delhi');

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Buy perfect money in India @Rs.70/- per pm Sell @Rs.58/- per pm,CALL 08054019105, Chandigarh, 160017

    --------------------------------------------------------------------------------------------------------------

    Buy/Sell Perfect Money At Reasonable Rates. We Provide Perfect Money At best Rates.
    We also sell buy Perfect Money, neteller and Bitcoin.

    Call us : +91 9517544444

    Gtalk : garrysingh1598

    Web.: www.sellperfectmoney64.com

    ReplyDelete