Encountering an error when attempting to save an ajax JSON response to a variable and receiving an

I am attempting to make an ajax call and store the JSON response in a variable. My goal is to display the JSON response in two separate Jqgrids, with one displaying half of the response and the other displaying the remaining half. I need some ideas on how to achieve this.

Although this is how I'm trying to store the JSON response, I'm encountering an undefined error when passing the variable to the alert() function.

var form_data;
$(searchBTN).click(function(event))
{
    $.getJSON("search?dealId=" + orderId,
        function(json) {
            form_data = json.CompanyName;
            checkdata();                                        
        });

    function checkData() {
        console.log(form_data);
        alert(form_data);
    }
}

Answer №1

It is recommended to review the format of your JSON data, especially the keys within the JSON array. It appears that you may be incorrectly accessing a variable. The "undefined" error indicates that the current key you are using is not defined in the JSON object. For testing purposes, you can try using the alert(JSON.parse(json)) method.

Answer №2

Here is an improved approach to achieve the desired outcome:

let formData;
$(searchButton).click(function(event)) {
    $.getJSON("search?dealId=" + orderId, function(data){
        formData = data.CompanyName;
        console.log(formData);
        alert(formData);               
    });
});

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

Can you explain the distinction between firstChild and childNodes[1]?

Exploring the distinction between child nodes and child elements within JavaScript DOM: For instance, var myTbodyElement = myTableElement.firstChild; versus var mySecondTrElement = myTbodyElement.childNodes[1]; Is it possible to interchangeably use firs ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

The donut chart in Chart.js is stuck in grayscale without any colorization

I just set up a donut chart using chart.js with the following code: <div id="chartContainer" style="height: 320px; width: 320px"> <canvas id="hoursFEContainer"></canvas> </div> To use chart.js, I downlo ...

Difficulty obtaining elements in Internet Explorer, however works fine in Chrome and Firefox

My <textarea> is set up like this: <textarea class="form-control notetext" id="{{this._id}}-notetext" name="notetext">{{this.text}}</textarea> I am using ajax to send data and load a partial webpage. After loading the content, I attemp ...

What is the best way to merge strings and JMESPath queries in order to construct a webhook payload?

I'm currently exploring the use of Cloud Custodian webhooks to generate tagged events in Datadog using the Datadog API. The code snippet below is almost functional, however, the tag for account_id is not being created in Datadog. When examining the b ...

Validating JSON data with REST assured

When it comes to validating Json Objects, I rely on https://code.google.com/p/rest-assured/wiki/Downloads?tm=2. import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import static org.hamcrest.MatcherAssert.asse ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...

Having trouble getting Highcharts SVG element to refresh? Looking to incorporate custom freeform drawing features within Highcharts?

I have implemented highchart for graph rendering and utilized the renderer to draw a custom line within the chart. I am looking for a way to recalculate and repaint this path whenever there is a change in data. The framework being used is highcharts-ng alo ...

Error generated by Jquery Ajax Call due to undefined response

I've been struggling with sending two variables to PHP using a Jquery Ajax call. It seems to work fine when async is set to false, but for some reason fails when it's set to true. Additionally, the code functions properly if only one variable is ...

The toggle for hiding and showing, along with changing the button color, is not functioning properly due to

I'm encountering a puzzling issue with a toggle that hides and displays information and changes color on click. The functionality works flawlessly on the page where I initially wrote the code. For instance, the button's background shifts colors w ...

Issue opening react modal dialogue box

I'm encountering an issue while trying to implement the headless ui modal. I'm attempting to trigger the modal.js script from my home.js file. In my home.js file, I have the following code snippet: function Home() { const [isOpen, setIsOpen] = ...

Converting JSON data into clickable URL links and retrieving information upon clicking

I have a dataset in JSON format. As I iterate through it, I'm inserting selected values into an HTML link element as shown below: getPatchList: function() { $.ajax({ url: "/returneddata" }).done(function(r ...

Steps to submit a JavaScript-generated output as the value in a form input field

I'm facing an issue that seems basic, but I can't seem to figure it out. I'm trying to create a binary string representing the 12 months of the year using 12 checkboxes: const checkboxes = [...document.querySelectorAll('input[type=check ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

I must update a bootstrap class name within multiple layers of divs by referring to the parent class

My code structure is set up like this: <div id="main-parent"> <div class="child2"> <div> child2 </div> </div> <div>child3</div> - - - - <div class="ch ...

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

Disable the scroll animation feature for certain IDs

I implemented JavaScript code to animate scrolling for each block with a specific ID. However, when I added Bootstrap's tabs, the animation interfered with the functionality of the tabs. Is there a way to disable the scroll animation specifically for ...

What is the proper way to construct a URL with filter parameters in the RTK Query framework?

I am facing difficulty in constructing the URL to fetch filtered data. The backend REST API is developed using .Net. The format of the URL for filtering items is as follows: BASE_URL/ENDPOINT?Technologies=some-id&Complexities=0&Complexities=1& ...

passing commands from a chrome extension to a content script

I want to set up a hotkey that will activate a function in my content script. The content script (main.js) is run when the page loads from my popup.js file. I've included the command in my manifest.json and I can see in the console log that it is tri ...

"Receive your share of the catch in a pop-up notification

Is there a way to determine if a user shared a result without using the social network's Javascript SDK? All sharing aspects (authorization, sharing, etc.) are done through popups on my domain. var popup = window.open('/api/share/' + servic ...