Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element:

function draw(json) {

  if (json["leaf_text"]) {
    stroke(100)
    ellipse(json["leaf_center_x"], json["leaf_center_y"], json["leaf_height"], json["leaf_width"]).rotate(json["leaf_rotate"]);
  }
  if (json["twig_text"]) {
    stroke(100);
    console.log("drawing twig....");
    line(json["twig_base_x"], json["twig_base_y"], json["twig_tip_x"], json["twig_tip_y"]);
  }
  if (json["branch_text"]) {
    stroke(150);
    line(json["branch_base_x"], json["branch_base_y"], json["branch_tip_x"], json["branch_tip_y"]);
    console.log("x1 " + json["branch_base_x"]);
    console.log("x2 " + json["branch_base_y"]);
    console.log("y1 " + json["branch_tip_x"]);
    console.log("y2 " + json["branch_tip_y"]);

  }
  if (json["trunk_text"]) {
    stroke(255);
    line(json["trunk_base_x"], json["trunk_base_y"], json["trunk_tip_x"], json["trunk_tip_y"]);
  }
}

When a successful AJAX response is received, this function is called as follows. However, an error occurs in the JavaScript console due to the draw function.

TypeError: json is undefined

My understanding is that the 'draw' function should be indifferent to whether or not 'json' exists and should only complain when it is passed an object of a different type. So why is it complaining about 'json' being undefined?

if (json["leaf_text"]) {
  $("#grow").click(
    function(e) {
      console.log("attempting ajax...");
      e.preventDefault();
      var csrftoken = getCookie('csrftoken');
      var open_parens = ($("#txt").val()).indexOf("(");
      var close_parens = ($("#txt").val()).indexOf(")");
      var child = $("#txt").val().slice(0, open_parens);
      var parent = $("#txt").val().slice(open_parens + 1, close_parens);

      $.ajax({
          url: window.location.href,
          type: "POST",
          data: {
            csrfmiddlewaretoken: csrftoken,
            child: child,
            parent: parent,
            mode: "grow"
          },
          success: function(json) {
            setup();
            draw(json);
            ...
          }
        },
        error: function(xhr, errmsg, err) {
          console.log(xhr.status + ": " + xhr.responseText);
        }

      });
  });

Answer №1

When utilizing the import feature for json, it is recommended to use a unique name as the parameter for the draw function. For instance, instead of simply using "draw(json)", consider naming it something like "draw(json_bar)" or when importing json, rename it as "import json as json_foo". This can help avoid any potential conflicts with other variables or functions.

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

Electron and React: Alert - Exceeded MaxListenersWarning: Potential memory leak detected in EventEmitter. [EventEmitter] has 21 updateDeviceList listeners added to it

I've been tirelessly searching to understand the root cause of this issue, and I believe I'm getting closer to unraveling the mystery. My method involves using USB detection to track the connection of USB devices: usbDetect.on('add', () ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

Create a package that is compatible with both node and browser environments

After successfully creating a node NPM package that acts as a wrapper for a specific JSON API using node's http, https, and querystring modules, I am now looking to expand its usability by making it compatible with browsers. This would involve replaci ...

Removing a particular post from the front-end with ajax in Django using Class Based Views

I have a Django application where I generate multiple posts using a loop. Now, I want to be able to delete specific posts in a similar way to how it works on Facebook. I've managed to retrieve the ID of the post using jQuery, but for some reason, I ca ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

Show results based on the selection of multiple checkboxes upon submission

When creating PHP pages to fetch data from databases, each checkbox is linked to a different page. I want to be able to check one or multiple checkboxes and then click the submit button to display the PHP pages that are linked to the checked checkboxes. Ho ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Is it acceptable to use "string" as a variable name in JavaScript?

Any tips on getting the code below to function properly? var x = 'name'; After that, I want to utilize the value inside x like a variable and assign it so that when I call for NAME, I get this outcome: var name = 'NAME'; Can this be ...

Triggering an Ajax request after a session times out

Hey everyone, I've been working on implementing a redirection to the login page in case of a session timeout during an AJAX call. Here's what I've accomplished so far: I created an action filter for all actions. public class AuthenticateFi ...

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

Edit the contents within HTML strings without altering the HTML structure

If I have a string of HTML, it might look something like this... <h2>Header</h2><p>all the <span class="bright">content</span> here</p> I am interested in manipulating the string by reversing all the words. For example ...

What steps can I take to redesign my React App in order to successfully send state to a component located on a separate route?

I am currently facing a challenge with restructuring my App in order to pass state via props from the SubmitProject Component to the Portfolio Component. The catch is that I still need to maintain separate paths for each component, such as /portfolio and / ...

Display function not functioning properly following AJAX request

I'm working on a functionality where I want to initially hide a table when the page loads, and then display it with the results when a form is submitted using Ajax. The issue I'm facing is that the code refreshes the page and sets the table back ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

Enhancing the efficiency of consolidating the key value distributed among various JSON entries

Currently, I am storing data in JSON format within a Redis ZSET with timestamps as scores. <timestamp_1> - [ { "key1" : 200 }, { "key2": 100 }, {"key3" : 5 }, .... {"key_n" : 1} ] <timestamp_2> - [ { "key50" : 500 }, { "key2": 300 }, {"k ...

Converting XML to JSON using WSO2 Conversion Tools

Whenever I attempt to convert XML to Json using XSLT mediator in WSO2, an error message stating "Payload could not be written as JSON" keeps appearing. Can someone provide assistance with resolving this issue? Appreciate any help in advance. ...

The React application is being continuously accessed by a node.js server and processed within async functions

Currently, I am utilizing React, MongoDB, Node.js, and Express in my project. The specific scenario I am facing involves the following code snippet within my component: renderWishlist(){ var quantity; var itemID; var tmp; var my ...

Steps for linking a keypress to trigger a specific action

I need help creating a script that will redirect to a URL when a button is clicked. Below is the code I have developed. HTML : <a id="#next" href="example.com">↵</a> <a id="#previous" href="example.com">↳</a> JS : $(document ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

jq allows you to incorporate the filtered results into a new filter

Is there a more efficient way to utilize the outcomes of a jq filter within another jq filter? Currently, I accomplish this task using xargs, but I believe there must be a simpler method with just a single jq execution. For instance: ]$ cat test.json { ...