Utilizing a JSON object passed from one JavaScript function to another: A comprehensive guide

After creating a function that returns JSON format through an ajax call, I received the following JSON data:

 {
    "communication": [{
        "communication_name": "None",
        "communication_id": "1"
    }],
    "hardware": [{
        "hardware_name": "XXXXXXXX",
        "hardware_id": "6"
    }],
    "Sofware": [{
        "software_name": "XXXXXX",
        "software_id": "3"
    }, {
        "software_name": "XXXXXXXXXXXXX",
        "software_id": "4"
    }]
}

The JavaScript function used to retrieve this response is as follows:

function getModelData(model_id, model_name){

     var xmlHttp = createXmlHttpRequestObject();

    try {
    xmlHttp.open("GET", "ajaxmodel_new.php?model_id="+model_id,true);
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status==200){
        var myJSONObject =  JSON.parse(xmlHttp.responseText)
        //alert(myJSONObject.communication[0].communication_name)
         }
    }
    xmlHttp.send(null);

    } catch (e){
    alert("Can't connect to server:\n" + e.toString());
    }
}

The correct response is being obtained. Another function is created to get the selected value from a dropdown menu:

<div id="selected_options">
                <select onchange="test()" id="selected_opt">
                <option value="0" selected>-Select-</option>
                <option value="1">Communication</option>
                             </select></div>
function test() {
    var get_id = document.getElementById('selected_opt');
    var result = get_id.options[get_id.selectedIndex].value;
    alert(result);
}

Objective

The goal now is to utilize the JSON response, specifically myJSONObject, in the test() function. How can the variable myJSONObject obtained in the getModelData() ajax function be utilized in the test() function?

Answer №1

My approach to parsing the JSON Object was a bit different.

First, on the PHP side, I create the object and store it in a variable, let's call it $JSONvar. Then, I simply use echo to output the variable.

Next, on the client side, here is how I handle the object:

var JsonObject = {};
var http = new XMLHttpRequest();
http.open("GET", url, true); // The URL that echoes the JSON string
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
    var responseTxt = http.responseText;
    myJSONObject = eval('(' + responseTxt + ')');
    test(myJSONObject);
 }
}
http.send(null);

The test function should be able to access the object like this:

function test(myJSONObject) {
var object = myJSONObject;
alert(object);
var get_id = document.getElementById('selected_opt');
var result = get_id.options[get_id.selectedIndex].value;
alert(result);
}

Answer №2

Execute the test() function within the xmlHttp.onreadystatechange method, making sure to pass the decoded object as an argument.

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

The Ajax call is expiring before completing

While working on my website, I encountered an issue with one of the PHP pages (test.php) that contains a list of queries under a while loop. When I try to call this page using an AJAX request, it terminates before its maximum execution time despite trying ...

Why isn't my classList .add method working properly?

I've created a video slider background on my website, but I'm having trouble with the Javacript for video slider navigation. When I click on the button to change the video, nothing happens. The console is showing an error message that says "Canno ...

A fresh checkbox was added to the page using Jquery Switchery to disable it

I'm having trouble disabling the Switchery checkbox. When I try to disable it, another Switchery checkbox appears on the page along with the one I previously defined: <div class="form-group"> <label class="col-md-2"> ...

Is it possible for me to create a lineString connecting two points in OpenLayers3?

I need to create a lineString connecting my two given points, such as [-110000, 4600000] and [0, 0]. ...

Using jQuery to drag a div and drop it to swap out an image in a different

I am looking to implement a drag and drop function where I can move elements from one div to another, each containing different images. However, I want the image displayed in the second div to change based on the element being dragged. For example: When d ...

Vue instance with non-reactive data

I am looking to store an object in Vue that will be accessible throughout the entire instance but does not need to be reactive. Typically, if I wanted it to be reactive, I would use 'data' like this: new Vue({ data: myObject }) However, since ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

Trouble with Component Lifecycle (ComponentDidMount) activation while switching tabs in TabBar?

After implementing the react-native-tab-navigator library to navigate between components, I encountered an issue where the componentDidMount lifecycle method works only once. I have reached out for help by posting a query on Github and have also attempted ...

JavaScript: Determining the point on a perpendicular line that is consistently a fixed distance away

I am currently working on finding a point that is equidistant from the midpoint of a perpendicular line. This point will be used to create a Bézier curve using the starting and ending points, along with this intermediate point. After calculating the perp ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow ou ...

I'm feeling lost trying to figure out how to recycle this JavaScript function

Having an issue with a function that registers buttons above a textarea to insert bbcode. It works well when there's only one editor on a page, but problems arise with multiple editors. Visit this example for reference: http://codepen.io/anon/pen/JWO ...

When the modal is closed, the textarea data remains intact, while the model is cleared

My challenge involves a simple modal that includes a text area. The issue I am facing is resetting the data of the textarea. Below is the modal code: <div class="modal fade" ng-controller="MyCtrl"> <div class="modal-dialog"> <d ...

kibana is throwing an error message that says it was expecting an end object but instead received a field name, potentially indicating an issue with

While attempting to create a complex boolean query with a fuzzy must requirement and multiple should requirements, including one with a wildcard, I am encountering an error message. Despite making adjustments to the syntax, I have been unable to resolve th ...

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

Select a particular item and transfer its unique identifier to a different web page. Are there more efficient methods to accomplish this task without relying on href links and using the $_GET

Could there be a more efficient method for transferring the ID of a specific motorcycle from index.php to inventory.php when it is clicked on, aside from using href and $_GET? Perhaps utilizing hidden fields or submitting a form through JavaScript? What ...

ReactJS: Alert for controlled form element

Utilizing inputs from Material-Ui, I am retrieving values from an API to populate these inputs. If the API does not return any values, the user must enter them manually. In my implementation, I am utilizing Hooks with the initial state defined as: const [ ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...