How to populate JSON data in input fields using Javascript in a best way?

Here we are discussing about how to populate JSON data in HTML input fields dynamically.This might be the best way to work on any kind of edit data/form operation.

Steps

1. Creating database and table
2. Connecting to database
3. Fetching data
4. Parsing data
5. Populating in the form

Creating database and table

Create a database(demo) make sure that you are using the right database name in your config.php file.

Run the following queries to create a table with some sample data


To create a table(user) 

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

To insert data into the table

INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `Password`, `City`) VALUES
(7, 'Rahul', 'Rajshekaran', 'Rahul@zzz.xxx', 'Rahul@123', 'Pune'),
(8, 'Mahesh', 'Krishna', 'Mahesh@xxx.xxx', 'Mahesh@123', 'Delhi'),
(9, 'Mahidar', 'kumar', 'Mahidar@xxx.com', 'Mahidar@123', 'Pune'),
(10, 'Mahpal', 'yadhav', 'mahipa@xxx.com', 'Mahipa@123', 'Delhi');



Connecting to database(config.php)


<?php
/* Database connection start */
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'root';
$dbName = 'demo';

//Create connection and select DB
$connection = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($connection->connect_error){
die("Unable to connect database: " . $connection->connect_error);
}
?>


Fetching data(index.php)


<?php
include('config.php');
//Check UserID set or not
if (isset($_GET['UserID'])) {
    $UserID = $_GET['UserID'];
    $sql = "SELECT * FROM user WHERE UserID='$UserID'";
    $result = mysqli_query($connection, $sql);
    if ((mysqli_num_rows($result)) > 0) {
        while ($row = mysqli_fetch_array($result)) {
            extract($row);
            $rows[] = array("Message" => "Success", "UserID" => $UserID, "FirstName" => $FirstName, "LastName" => $LastName, "Email" => $Email, "City" => $City);
        }
    } else {
        $rows[] = array("Message" => "No Data");
    }
} else {
    $rows[] = array("Message" => "Error");
}
echo json_encode($rows);
mysqli_close($connection);
?>



Parsing data with JQuery


//Script
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function userEdit(UserID) {
    $(document).ready(function () {
        $.getJSON("http://localhost/demo/user.php?UserID=" + UserID,
            function (json) {
                for (var i = 0; i < json.length; i++) {
var Message = json[i].Message;
document.getElementById("Message").innerHTML = Message;
                    $.each(json[0] , function (key, value){
                        $('input[id='+key+']').val(value);
                    });
                }
            });
    });
}
</script>
//CSS
<style type="text/css">
    body{
        position: absolute;
        width: 600px;
        height: 200px;
        z-index: 15;
        top: 40%;
        left: 30%;
        margin: -100px 0 0 -150px;
    }
    .box{
        background: #43c181;
        padding-top: 10px;
        padding-left: 60px;
        padding-bottom: 30px;
        width: 500px;
        height: auto;
    }
    .btn-success{
        padding: 5px;
    }
</style>


*Place the above code in the head section of your HTML.

Populating in the form


<body>

<div class='box'>

<h4 id="Message"></h4>

<form action='#' method='post' id='Form' enctype='multipart/form-data'>

<div class="col-md-10">
            <label>First Name</label>
            <input type="text" id="FirstName" class="form-control" name="FirstName" placeholder='First Name'/>
        </div>

 <div class="col-md-10">
            <label>Last Name</label>
            <input id="LastName" name="LastName" class="form-control" type="text" placeholder='Last Name'/>
        </div>

 <div class="col-md-10">
            <label>Email</label>
            <input id="Email" name="Email" class="form-control" type="text"
                   placeholder='Email'/>
        </div>

</form>

</div>

</body>

//Call function
<script>
userEdit(UserID = 7);
</script>


Result


*Please subscribe to PHP Javascript for more.

* Display JSON data in dropdown

Display JSON data in a table


7 comments:

  1. which is really a immature share of the problems a lot of people unrecorded with sect now, but but making improved lives for group that's direction on feat them much , keeping them punter aid and making certain their kids get enlightened.
    send cremated remains

    ReplyDelete
  2. When it comes to finding the Best Forex Trading Platform in India, Winprofx stands out as a trusted and beginner-friendly choice for both new and experienced traders. Designed with Indian traders in mind, Winprofx offers a seamless trading experience with advanced tools, real-time analytics, fast execution, and low spreads, making it one of the top-performing forex platforms in 2025. Whether you're looking to trade major currency pairs, explore commodities, or learn the ropes through demo accounts, Winprofx provides a secure and transparent environment that prioritizes your growth. What truly sets it apart is its focus on forex education—ideal for Indian traders who want to develop strong trading skills and strategies before risking real money. With multilingual customer support, INR-based deposits, and access to some of the Top Forex Brokers, Winprofx bridges the gap between global opportunities and local convenience. It supports quick withdrawals, advanced charting tools, and even funded account options for those who qualify. If you're looking to trade confidently in the dynamic forex market while enjoying local support and international-level features, Winprofx is undeniably the Best Forex Trading Platform in India to consider in 2025.

    Best Forex Trading Platform in India-

    ReplyDelete
  3. Free Funded Forex Account – A Gateway to Risk-Free Trading:

    A Free Funded Forex Account – A Gateway to Risk-Free Trading gives aspiring traders a unique opportunity to trade in the real market without investing their own money. These accounts are offered by proprietary trading firms that provide traders with capital after they pass an evaluation or basic skill test. Since traders trade with the firm’s funds, there is no personal financial risk involved, making it an excellent option for beginners and experienced traders who want to grow without the fear of losing their savings. Profits are shared between the trader and the firm, creating a win–win model. With structured challenges, professional tools, and proper risk guidelines, free funded forex accounts empower traders to build confidence, sharpen their strategies, and experience real-market conditions safely and responsibly.
    Contact us Address – 1st Floor, The Sotheby Building, Rodney Bay, Gros-Islet, SAINT Lucia P.O Box 838, Castries, Saint Lucia Phone no – +97144471894 Website – https://winprofx.com/

    ReplyDelete
  4. Forex Trading Platforms are specialized software applications that allow traders to access the global foreign exchange market and execute trades in real-time. These platforms provide a range of tools and features, including live price charts, technical analysis indicators, news feeds, and risk management options, to help traders make informed decisions. Leading platforms often support multiple account types, automated trading through expert advisors or bots, and secure fund management. Whether you are a beginner or an experienced trader, a reliable forex trading platform ensures smooth execution, fast order processing, and a transparent environment for trading currencies efficiently.
    Contact us Address – 1st Floor, The Sotheby Building, Rodney Bay, Gros-Islet, SAINT Lucia P.O Box 838, Castries, Saint Lucia Phone no – +97144471894 Website – https://winprofx.com/

    ReplyDelete
  5. In India, the top forex brokers are those that are registered with the Securities and Exchange Board of India (SEBI) and legally allowed to offer currency derivatives trading (INR pairs like USD/INR, EUR/INR, GBP/INR, JPY/INR) on recognized exchanges such as the National Stock Exchange and Bombay Stock Exchange. Some of the most popular and trusted brokers include Zerodha, known for its user-friendly Kite platform and low fees; Angel One, which offers good research tools and competitive pricing; ICICI Direct and HDFC Securities, both backed by major banks with reliable customer support and integrated services; Upstox, a discount broker with easy-to-use apps; and other SEBI-registered names like Sharekhan and Motilal Oswal. Choosing a regulated broker ensures that your forex trading stays within Indian legal frameworks and gives you investor protection and access to official exchange infrastructure.
    Contact us Address – 1st Floor, The Sotheby Building, Rodney Bay, Gros-Islet, SAINT Lucia P.O Box 838, Castries, Saint Lucia Phone no – +97144471894 Website – https://winprofx.com/

    ReplyDelete
  6. A **forex trading platform** is an online software application that enables traders to buy and sell currencies, view live exchange rates, analyse price charts, and execute trades electronically. These platforms are provided by brokerage firms and act as the interface between the trader and the financial markets, offering features like real-time quotes, technical indicators, risk-management tools, news feeds, and order types to help users make informed decisions. In India, forex trading platforms offered by SEBI-registered brokers allow legal trading of currency futures and options (such as USD/INR and EUR/INR) on recognized exchanges, ensuring compliance with regulatory standards. Good platforms are user-friendly, fast, and secure, making it easier for both beginners and experienced traders to access the currency market from computers or mobile devices.

    ReplyDelete
  7. A **forex trading platform** is an online software application that enables traders to buy and sell currencies, view live exchange rates, analyse price charts, and execute trades electronically. These platforms are provided by brokerage firms and act as the interface between the trader and the financial markets, offering features like real-time quotes, technical indicators, risk-management tools, news feeds, and order types to help users make informed decisions. In India, forex trading platforms offered by SEBI-registered brokers allow legal trading of currency futures and options (such as USD/INR and EUR/INR) on recognized exchanges, ensuring compliance with regulatory standards. Good platforms are user-friendly, fast, and secure, making it easier for both beginners and experienced traders to access the currency market from computers or mobile devices.

    ReplyDelete

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts