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

Vue component fails to react to updates from Vuex

Currently, I am developing a system to facilitate the management of orders at a shipping station. Although I have successfully implemented the initial changes and most of the functionality, I am encountering an issue where one component fails to update ano ...

Update the Access Key Id from the root account to the IAM user in AWS IAM

I have a question, Utilizing elastic beanstalk for deploying Python Django applications. During the initialization process with eb init, I utilized the root Access Key ID and Secret Access Key to create the instance. Recently, I came across information ...

Attempting to provide varying values causes If/Else to become unresponsive

I've implemented a function that scans a file for a specific term and then outputs the entire line as a JSON object. Strangely, when I include an else statement in the logic, an error occurs: _http_outgoing.js:335 throw new Error('Can\& ...

Click event to focus on AngularJS TinyMCE textarea

My current project utilizes the tinymce text editor in combination with the angularJS framework. I obtained the directive from here and successfully integrated the editor using the provided example on GitHub! Initially, everything was working smoothly wit ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

The values of React children props will always remain consistent

While attempting to incorporate an ErrorBoundary HoC component for error handling following the guidelines from React16 documentation, I designed the ErrorBoundary component as a PureComponent. It became apparent that the children props remained consistent ...

What could be causing my JavaScript function to produce repeated letters with just one key press?

After implementing a code that generates different variables based on the 'truth' variable, I encountered an issue. Everything works flawlessly when 'truth' is set to "name," but as soon as I switch it to "email," any keystroke results ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

I'm having trouble getting the app.locals function within a button to work on my EJS template. Can anyone help troub

Below is the content of my script named agents.js: var express = require('express'); var router = express.Router(); var app = express(); // Is it appropriate to call Express like this twice? router.get('/', function(req, res, next) { ...

issue in jquery: ajax promise not returning any value

My code snippet: var testApp = (function($){ var info = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function fetchInfo(opt) { return new Promis ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...

Jmeter - Unable to retrieve sessionId while sending Body data

HTTP request 1 - GET I used a Regular Expression Extractor to grab the sessionId, and then passed it as a reference variable in the body data of another request. { "sessionId":"${sesid}" } The response returned was a 400 bad request. Interestingly, pas ...

The bot believes it's jamming out to some tunes, but there's nothing but silence in the realm

Essentially, a slash command is utilized to initiate playing a music video in Distube. It plays for approximately 30 seconds and then abruptly stops, even though the queue indicates that the music is still playing. There are no errors appearing in my termi ...

Utilizing Vue.js to display raw HTML content in elements.io table

I am trying to display HTML data in a table using Vue.js. new Vue({ el: "#app", data: { todos: [ { text: "<p>Learn JavaScript</p>", done: false }, { text: "<p>Learn Vue</p>", done: false ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

Progress bar indicating the loading status of an AJAX script

I am facing a challenge with creating a progress bar in AJAX. The entire page is loaded through AJAX, and one of the webpage elements uses AJAX to fetch large rows from the database. I have attempted to implement a progress bar within this script using a ...

Encountered an error with the opcode during deployment of migrations

Encountering an error while running the truffle migration command, despite trying several solutions without success. PS C:\Users\Jatin\OneDrive - nsut.ac.in\Desktop\Truffle\web> truffle migration Compiling your contracts... ...

The element 'stripe-pricing-table' is not a recognized property of the 'JSX.IntrinsicElements' type

I am currently trying to incorporate a pricing table using information from the Stripe documentation found at this link. However, during the process, I encountered an issue stating: "Property 'stripe-pricing-table' does not exist on type &ap ...

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

Is the text in bold format or not detectable in contenteditable mode?

I am currently working on developing a custom text editor using the built-in contenteditable feature in HTML. I am trying to figure out how to determine whether the selected text is bold or not within the editor. This is what my current setup looks like: ...