Updating a multitude of values efficiently

When updating multiple fields using ajax, I retrieve a row from the database on my server, JSON encode the row, and send it as the xmlhttp.responseText.

The format of the response text is as follows:

{"JobCardNum":5063,"IssueTo":"MachineShop","Priority":"High" ...lots of data}

After parsing the response text in the browser, I start the process of updating values like this:

var obj = JSON.parse(info);
document.getElementById("JobCardNum").value = obj.JobCardNum;
document.getElementById("IssueTo").value = obj.IssueTo;
document.getElementById("MachineShop").value = obj.MachineShop; 
....... lots of similar statements

Since the element id matches the column names, I wondered if there was a way to loop through my JavaScript object and set all the values. Any suggestions?

Answer №1

The following code snippet can be used to loop through a JSON object and update its values dynamically.

for (let property in data) {
  if (data.hasOwnProperty(property)) {
    let element = document.getElementById(property);
    if(element) {
      element.value = data[property];
    }
  }
}

Answer №2

Here is how you can solve the problem by utilizing the Object.keys and Array.forEach methods:

let data = JSON.parse(information);

Object.keys(data).forEach(function(key){
    let element = document.getElementById(key);
    if (element) element.value = data[key];
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AWS Cognito - ECS Task Fails to Start

I'm facing an issue with using JavaScript to execute a task in ECS Fargate. AWS suggested utilizing Cognito Identity Credentials for this task. However, when I provide the IdentityPoolId as shown below: const aws = require("aws-sdk"); aws.co ...

Tips for setting the textfield value in JSP using Javascript

I am in need of a way to create a random number that will be displayed in the textfield once the user clicks on the "Generate" button. Can someone guide me on how to assign the value of the "output variable" to the "randomNum" textfield? Sample HTML code: ...

"Exploring the Dynamic Display of Ajax with HTML5 Canvas

This is my first time exploring the world of ajax, and I'm finding it quite challenging to grasp the concept and functionality. What I aim to achieve: I envision a scenario where I can freely draw on a canvas and simply hit save. Upon saving, the da ...

Functionality of click events disabled upon loading of ajax content

Can anyone help me figure out how to make the function "live('click',function()" work after an ajax call that returns content with html(data)? I've been searching for 4 hours and haven't made any progress. This part of the code is work ...

The destination you are trying to reach through a POST request at this time is unavailable

I'm encountering an issue while attempting to send an AJAX request to a separate controller within my view. Here is how my form for the AJAX request appears. I have also experimented with sites_search_results_index_path, which according to my routes ...

Check out how to utilize the jQuery .ajax Post method in a function

Can an AJAX POST be directed to a specific function in a PHP file? $.ajax({ type: "POST", url: "functions.php", //is there a way to specify a function here? data: "some data...", success: function(){ alert('Succ ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

Refreshing the page when the hide/show button is clicked with jQuery

I have a situation where I am using jQuery to toggle the visibility of a div by clicking on show/hide buttons. However, I am facing an issue where the code does not work as intended. Every time I click the buttons, the div reverts back to its original stat ...

`Assemble: Store the newly created Stripe "Client Identity" in a designated container`

Upon a new user registration on my website, I aim to create a Stripe customer ID along with username and email for database storage. The process of customer creation seems to be working as evidenced by the activity in the Stripe test dashboard. However, h ...

The Jquery calculation feature sometimes mistakenly adds an incorrect value before calculating the correct value

Working on a calculator that accurately computes the field price and displays it, but facing an issue where the correct answer seems to merge with another value (likely from data-price as they match). Snippet of the code: var updateTotal = function() { ...

Transforming MySQL data into JSON format for a URL

While attempting to convert MySQL data to JSON using PHP, I encountered a blank page issue when working with a database collation of utf8_general_ci. <?php include("config.php"); header('Content-Type: text/html; charset=utf-8'); $result = my ...

What is the best way to suppress a warning message following an AJAX request?

Struggling to solve this dilemma. I've successfully suppressed a warning with: error_reporting(E_ERROR | E_PARSE). However, when making an ajax request to load data that triggers the same warning I'm trying to suppress, it still appears in my in ...

What could be the reason for the malfunction of Bootstrap Js in my template?

This question focuses on understanding how something works rather than just fixing it. I really enjoy learning about this. Currently, I am involved in a project that combines VueJS and Symfony. One of the things I would like to achieve is using Bootstrap ...

Using an Ajax Post request to trigger a JavaScript function

Looking to execute a JavaScript function with a PHP variable, I utilized an AJAX request to send the variable named [filename] for executing the JavaScript function as follows: upload.php <script> function prepareforconvert(filenamse){ ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...

Pass data to PHP using AJAX

Is it possible to pass the variable rowNumber to the PHP file dataSource in this code? function getData(dataSource, divID,rowNumber) { if(XMLHttpRequestObject) { var obj = document.getElementById(divID); XMLHttpRequestObject.open("GET", dataSo ...

CSS styling failing to meet desired expectations

Two different elements from different panels are using the same CSS styles, but one displays the desired text while the other does not. The CSS file in question is named grid.css. To see the issue firsthand on my live website, please visit: I am uncertai ...

Looking to iterate through a dataframe and transform each row into a JSON object?

In the process of developing a function to transmit data to a remote server, I have come across a challenge. My current approach involves utilizing the pandas library to read and convert CSV file data into a dataframe. The next step is to iterate through t ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Can a table with a checkered pattern be created in Ember.js with just Handlebars and ember-composable-helpers?

I'm new to working with Ember.js and I am attempting to create a simple checkered table. In my project, I am utilizing Bootstrap 4, ember-composable-helpers, and Handlebars. Is there anyone who can guide me on achieving this goal WITHOUT the use of ja ...