Leveraging JSON for parsing xmlhttp.responseText to auto-fill input fields

Is there a way to utilize JSON for parsing xmlhttp.responseText in order to populate textboxes? I've been struggling to achieve this using .value and .innerHTML with the dot notation, along with b.first and b.second from the json_encode function in the loadTextBox.php file (shown below), but the textboxes remain empty.

Code from the main page:

function loadDoc()
{
   var xmlhttp;

   // code for IE7+, Firefox, Chrome, Opera, Safari
   if (window.XMLHttpRequest)
   {
      xmlhttp=new XMLHttpRequest();
   }
   //code for IE6, IE5
   else
   {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

   xmlhttp.onreadystatechange=function()
   {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         var doc = window.document.createElement("doc");
         var a = xmlhttp.responseText;
         var b = JSON.parse(a);
         document.getElementById("textbox").innerHTML=b.first;
         document.getElementById("textbox2").innerHTML=b.second;
      }
   }

   xmlhttp.open("GET","loadTextBox.php?id=4",true);
   xmlhttp.send();
}

Code from loadTextBox.php:

<?php
---Placeholder for correct DB login info---

$result = $mysql->query("SELECT column_one FROM table_one");

while ($row = $result->fetch_object())
{
   $queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>

Answer №1

Tested thoroughly and confirmed to be functioning correctly. Use this code snippet as a foundation for achieving your desired outcome:

let endpoint = "YOUR.php"

let ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", endpoint, true);
ajaxRequest.send(null);

ajaxRequest.onreadystatechange = function () {
     if (ajaxRequest.readyState == 4 && (ajaxRequest.status == 200)) {

        console.log("Ready to process data")            
        
        let jsonData = JSON.parse(ajaxRequest.responseText);
        console.log(jsonData);
        console.log(jsonData.first);

    } else {
        console.log("Data not yet ready for processing")            
    }
}

This code assumes that the JSON output is properly formatted as you mentioned:

{"first":"example","second":"demo"} 

Answer №2

After extensive troubleshooting, I identified the root cause of the issue at hand. It appears that extra tags were being transmitted due to redundant tags present in my DB information file. These unnecessary tags were delivered in the responseText as {"first":"radim","second":"radi"}, causing errors in the segment related to ---Placeholder for correct DB login info---. By making adjustments such as changing .innerHTML to .value, I was able to rectify the problem.

Updates made to the main page code:

function loadDoc()
{
   var xmlhttp;

   // Revised code for better compatibility across browsers
   if (window.XMLHttpRequest)
   {
      xmlhttp=new XMLHttpRequest();
   }
   else
   {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

   xmlhttp.onreadystatechange=function()
   {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         var a = JSON.parse(xmlhttp.responseText);
         document.getElementById("textbox").value=a.first;
         document.getElementById("textbox2").value=a.second;
      }
   }

   xmlhttp.open("GET","loadTextBox.php?id=4",true);
   xmlhttp.send();
}

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

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

Searching for nested divs with the same class name in jQuery can be achieved by using the

Need assistance in locating all divs with a specific class name. Some divs may have nested divs with the parent div's class name. Take this scenario for example: <div class="myForm"> <div class ="myDiv"> <div class ="myDiv"> ...

Is there a way in Javascript to apply quotation marks to each value within an array individually?

I've created a function that retrieves and displays values from a CSV file. Here is the code for the function: var IDArr = []; var fileInput = document.getElementById("csv"); readFile = function() { console.log("file uploaded") var reader = new ...

Using JQUERY to customize the quantity box in Magento's list.phtml file

I'm looking to incorporate a quantity box into Magento's list.phtml file. The current code for the box is as follows: <div> <button type="button" style=" margin-left:185px; min-height:48px;"title="<?php echo $this->__(&apos ...

Ensure that a div with fluid width remains consistently centered within another div

I have a bunch of boxes filled with content. The number of boxes in each row varies depending on the width of the browser window. Is there a way to ensure that all the boxes are always horizontally centered on the page? For guidance, you can check out th ...

Unexpected outcome from the zero-fill operator (>>>) in Javascript's right shift operation

Initially, is (-1 >>> 0) === (2**32 - 1) possibly due to extending the number with a zero on the left, transforming it into a 33-bit number? However, why does (-1 >>> 32) === (2**32 - 1) as well? I had anticipated that after shifting the ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...

Utilizing Airbnb's iCalendar Link for Automation

I have obtained the iCalendar link for an Airbnb listing. Upon visiting the link in any browser, it automatically triggers the download of a .ics iCalendar file. My goal is to develop an application that can sync with this specific Airbnb listing's iC ...

Update the text content in the specific span element when the class attribute matches the selected option in the

How can I dynamically update text inside a span based on matching classes and attributes without hardcoding them all? An ideal solution would involve a JavaScript function that searches for matches between span classes and select field options, updating t ...

Implementing Checkbox Functionality within a Dropdown Menu using AngularJS or JavaScript

I am interested in finding a multi-select checkbox solution similar to the one demonstrated here: Instead of using jQuery, I would prefer options in AngularJS or pure JavaScript. Does such a solution already exist in these frameworks, or is there guidance ...

What is the optimal way to organize OATH and views in a Grails RESTful client application?

Greetings! I am delving into the world of Groovy and Grails for the first time. My goal is to create a Grails Restful Client App (potentially a liferay portlet) that can fetch JSON data and present it elegantly in views while adhering to best practices. F ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

avoid selecting a d3 table

I'm currently learning about creating tables in D3 and I have a question regarding when to use ".select()": For example, when constructing circles: var circles = svg.selectAll("circle") .data(dataSet) .enter() .append("circle") .att ...

What is the best way to recover past messages from a channel?

I am working on a bot that is supposed to be able to retrieve all messages from a specific server and channel upon request. I attempted to use the channel.messages.cache.array() method, but it only returned an empty array []. How can I efficiently fetch ...

What is the best way to add a new item to an object using its index value?

Can the Locations object have a new property added to it? The property to be added is: 2:{ name: "Japan", lat: 36, lng: 138, description: 'default', color: 'default', url: 'default' } The current Location ...

A conflict with the Ajax file is causing an automatic logout

In my Rails application, there is a page with a table that uses partial AJAX to increase the capacity attribute in a time entity. You can view the visual representation of the table here. By clicking the plus/minus button, the capacity attribute increases ...

Tips on tallying the frequency of items in a state array

I'm currently working on an application in which clicking a button adds the item's value to the state. The button is clickable multiple times, allowing the same item to be added multiple times in the state array. My current code snippet: export ...

Efficient method for parsing multiple JSON objects simultaneously to create a single aggregated JSON output

When it comes to efficiently parsing and aggregating multiple JSON data sets, the key is to effectively merge them into a final output. Let's consider the following: Json1 : [ { "id":"abc", "name" : "json" }, ... (10k more JSON objects) ] Jso ...

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

keep jquery scrolltop position consistent after receiving response

I created a code to show the chat history, and everything seems to be working fine. However, I encountered an issue where old posts are displayed all at once when scrolling up the div. In order to continue scrolling smoothly, I included this code $("#messa ...