Search code examples
javascriptajaxformsjspxmlhttprequest

XMLHttpRequest, AJAX, JSP, Load data into form


If the object contains more fields than what are referenced in the form, then it breaks, how can I prevent this (https://jsfiddle.net/a4v7p2xg/2/) the snippet below works.

var data = {
  "firstname": "David",
  "lastname": "Garcia"
};

$( document ).ready(function() {
Object.keys(data).forEach(key => document.querySelector(`input[data-name="${key}"]`).value = data[key]);
});
<!doctype html>
<html lang="en">

  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <!-- JS -->

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <title></title>
    <style type="text/css">
      body {
        font-family: 'Open Sans', Arial, helvetica, sans-serif;
        color: #333333
      }

    </style>
  </head>


  <body style="" class="">
    <div class="container px-4">
      <div class="row gx-5 align-items-center">
        <div class="col-2 p-1">First Name</div>
        <div class="col p-1"><input name="firstname" data-name="firstname" class="form-control" id="firstname" type="text" /></div>
      </div>
      <div class="row gx-5 align-items-center">
        <div class="col-2 p-1">Last Name</div>
        <div class="col p-1"><input name="lastname" data-name="lastname" class="form-control" id="lastname" type="text" /></div>
      </div>
    </div>
  </body>

</html>


Solution

    • First off, instead of using XMLHTTPRequest, you should be using the fetch api, built-in to JS. See this answer.
    • Secondly, you can set the value of the inputs after adding data-name attributes to each input which corresponds to the key of the value of the object you want to set its value to . Here's how I would do that:
    function addToForm(data){
        Object.keys(data).forEach(key => document.querySelector(`[data-name="${key}"]`) == null ? 0 : document.querySelector(`[data-name="${key}"]`).value = data[key])
    }