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

Making a request using AJAX to retrieve data from an API

Looking to create an API GET request using ajax? Want a jquery function that takes an api key from the first input field and displays a concatenated result on the second input field (#2)? The goal is to make the get request to the value shown in the 2nd ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

Filter ng-repeat using OR condition for property

I'm trying to filter a list based on a model value entered in a text box. For example: var person={}; person.Id=1; person.Name="Test 1"; person.PetName="Rest 1" var persons=[]; persons.push(person); person.Id=2; person.Name="Test ds"; per ...

What is the most effective method for fetching images from MongoDB?

I'm currently working on a web application that uses MongoDB's GridFS to store and retrieve images. However, I'm facing an issue where retrieving images from the database takes significantly longer than expected when a user makes a request. ...

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

Testing a function within a React functional component using jest.spyOn with React Testing Library can be accomplished with the following steps:

I'm currently working on a React component and I'm facing an issue with unit testing using React Testing Library. Specifically, I'm having trouble testing the handleClick function of the TestComponent using jest.spyOn(). Can anyone provide s ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Issue with Sequelize Associate function not functioning correctly

I've been attempting to connect two tables in Sequelize, but I keep encountering the SequelizeEagerLoadingError indicating that one table is not associated with the other, despite trying all the suggested solutions on this platform. The tables in que ...

Leverage object properties as data table field values in VueJS

In my current project, I am utilizing VueJS (version 2.5.9) to display and modify data tables within an administrative application. Initially, I used a basic Grid component for the data table, following an example provided here. However, I came across an e ...

Is there a way to retrieve the id of a jQuery autocomplete input while inside the onItemSelect callback function?

I am currently utilizing the jquery autocomplete plugin created by pengoworks. You can find more information about it here: Within the function that is triggered when an entry is selected, I need to determine the identifier of the input element. This is i ...

How can a command in a test be executed that is located within a specific "section" in Nightwatch?

I've been utilizing nightwatch for my test automation. Within my page object, I have a "section" containing various commands. However, when attempting to call these commands in the test script, I encountered an error stating "section is not a function ...

Enhanced hierarchical organization of trees

I came across this code snippet: class Category { constructor( readonly _title: string, ) { } get title() { return this._title } } const categories = { get pets() { const pets = new Category('Pets') return { ge ...

Transforming a JSON object property value from an array into a string using JavaScript

I am facing an issue with an API call I am using, as it is sending objects with a single property that contains an array value (seen in the keys property in the response below). However, I need to work with nested arrays in order to utilize the outputted v ...

Go all the way down to see the latest messages

I have developed a messaging system using Vue. The latest messages are displayed from bottom to top. I want to automatically scroll to the end of a conversation when it is clicked and all the messages have been loaded via axios. Conversation Messages Comp ...

Exploring the integration of AJAX and jQuery with Django 1.3

I am completely new to the Django framework, web development, and Python. Currently, I am trying to incorporate AJAX into my project but struggling to find a working sample. I need assistance with integrating AJAX or jQuery within a Django 1.3 project. Cu ...

Ensuring consistency in aligning float elements

I've been struggling to create a concept design for my internship project. I aim to have a page with six clickable elements (images). When one is clicked, the others should disappear and the active one moves to the top. I managed to achieve this using ...

Tips on maintaining the Parent menu in a hovered state when the mouse is over the child menu within a Dropdown Menu

I have been working on creating a dropdown menu that functions correctly. However, I am facing an issue where the top menu, when hovered, turns white, but as soon as I move down to the submenus, the top menu reverts back to its original color. Is there a ...

Utilizing Dynamic Image Sources in Vue.js with the Help of APIs

Can someone help me figure out how to solve this issue? I have an API that returns a base64 image, and I want to load this image on my site. Any suggestions on where or how I should implement my function? This is the API call located in the methods: metho ...

Tips for adjusting the current window location in Selenium without having to close the window

I am currently working with seleniumIDE My goal is to have a Test Case navigate to a different location depending on a condition (please note that I am using JavaScript for this purpose, and cannot use the if-then plugin at the moment). I have tried using ...