Error encountered: Unable to retrieve an object variable in a member method due to undefined "this.form" in JavaScript

Here is the code that I am currently using:

 var frontPic = e.target.files[0]
 var frontPicName = frontPic.name
 var salonId=$("#salonId").val()
 upload = new Upload(frontPicName, salonId)
 upload.resize(frontPic)

To invoke the code above:

function Upload(filename, salonId){

    var form = new FormData()
        form.append("filename", filename)
        form.append("salonId", salonId)
};

Upload.prototype.resize = function(file){
    $.canvasResize(file,
    {
        width: 400,
        height: 0,
        crop: false,
        quality: 100,
        callback: function (data)
        {
            alert(data)
            // Add file data
            this.form.append("file", $.canvasResize('dataURLtoBlob', data));
            $('body').css("background", "url("+data+")")
        }
    });
}

While my alert(data) seems to be functioning correctly, the resizing process itself appears to be executing smoothly.

However, an error message stating this.form is undefined pops up for the line

this.form.append("file", $.canvasResize('dataURLtoBlob', data));

What would be the correct syntax in this case?

Answer №1

Your code has a couple of issues that need to be addressed:

  • The form variable is being declared locally within the constructor function instead of as a property of the object.

  • The reference to this inside the callback function does not point to the correct object, so it needs to be stored in a local variable for proper access.

function ImageUpload(filename, salonId){

    this.form = new FormData()
    this.form.append("filename", filename)
    this.form.append("salonId", salonId)
};

ImageUpload.prototype.resize = function(file){

    var self = this;

    $.canvasResize(file,
    {
        width: 400,
        height: 0,
        crop: false,
        quality: 100,
        callback: function (data)
        {
            self.form.append("file", $.canvasResize('dataURLtoBlob', data));
            $('body').css("background-image", "url("+data+")")
        }
    });
}

Answer №2

this may be linked to a different context. It's advisable to establish a pointer before invoking $.canvasResize.

Upload.prototype.resize = function(file){
    var self = this;
    $.canvasResize(file,

subsequently, swap out this with self.

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

Identifying Touch Interaction exclusively on WebGL Canvas within threejs

Currently, I am developing a threejs application that requires input from HTML buttons and utilizes Raycast Detection on touch within threeJS. The issue I am encountering is that when the user clicks an HTML button, the Raycast function is triggered as we ...

The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page. // route.js module.exports = function(app, passport) { app.use('/profile&apos ...

Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=. Am I facing any obstacles in using either the f ...

Implementing filters and pagination in getserversideprops for next js deployment

I'm currently working on implementing filter and pagination features for my product list page. However, I am unsure how to pass values to getServerSideProps in the same way that we fetch data in useEffect and use the updated values as dependencies in ...

Using the Parallax Effect in React

I'm currently working on implementing a parallax effect in React and I've encountered an error that's giving me trouble: Below is the snippet of JavaScript code I have for the parallax effect: export const parallax = document.getElementsBy ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

What are the drawbacks of performing CPU-heavy tasks within an event loop?

According to a tutorial I recently came across, Node's event-loop approach is recommended for handling I/O intensive tasks such as reading from a hard disk or using network operations. However, it is advised against using this approach for CPU-intensi ...

Ensuring the cookie remains active throughout various subdomains

After implementing code to set a cookie on example.com, I noticed an issue with it carrying over to the subdomain dogs.example.com. <script> document.cookie="cid1={{utm_campaign}}; path=/;" </script> The {{}} is part of Google-Tag-Manager s ...

Obtain the parameter value from the resolve function in ui-router

Using window.open, I plan to open a URL such as https://localhost:3000/new?HostId=8Ocs_Onuv1wowozxAAAS&_host_Info=excel%7Cweb%7C16.00%7Cen-us%7Cc8b501ce-c51d-b862-701e-5c623e1a70e0%7CisDialog. The site https://localhost:3000 hosts a MEAN stack applica ...

Ensure that both Vue methods are executed synchronously

I am working with two Vue methods: (1) this.retrieveSavedSearches() (2) this.updateDefaultSelectOption() Is there a way to ensure that method (2) only executes after method(1) has completed its execution? ...

Update the existing JSON object by incorporating a new property:value pair

I currently have a JSON object structured as follows: var data = {ID: 123, Name: "test"} My goal is to include an additional property and value in the data object based on a condition set by an inline if statement. The desired output should be: data = ...

I require JSON formatting containing the necessary values for integration with the Flot Chart plugin

I need assistance with retrieving data from a mysql database to populate a chart using the Flot plugin. According to the documentation, the data format should be an array of dots: [ [x1, y1], [x2, y2], ... ]. In my scenario, I am looking to extract date an ...

Use the .replace() method to eliminate all content on the page except for the table

Extracting a table from a page that has been loaded through .ajax() in queue.htm has proven to be challenging. I am attempting to utilize .replace(regex) in order to isolate the specific table needed, but the process is unfamiliar to me. $j.ajax({ ...

Close button for colorbox modal window containing an iframe

I'm currently utilizing colorbox for a modal popup, and the content of the popup is being sourced from a URL. Since it's displayed within an iFrame, I'm wondering how I can incorporate a close button to the modal popup. Thank you The follo ...

Is it better to create routers on the client side using React, or should one opt to use Express router on the server

As I embark on my journey to learn React, I have been delving into books for guidance. However, one question that lingers in my mind is how to elevate my application to a more professional level. I recently came across react-router-dom and explored the i ...

Tips for sending a JavaScript variable within a div's ID in a Twig loop?

How can I insert a JavaScript variable into the ID of a div inside a Twig loop? Here is my unsuccessful attempt: <script type="text/javascript"> id = 0; </script> {% for element in parent.elements %} <div id="mydiv"> ...

Shadows in Three.js cascading onto clear surfaces with a low-resolution twist

Here's the problem I'm facing: I want to remove the shadows on the text but changing the shadowMap resolution doesn't seem to have any effect. This is the code snippet responsible for creating the mesh: var materialArray_Flying = [ ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...

My PUT request is encountering difficulties with axios and not being successfully processed

Using the MERN stack, I am developing a basic website that includes CRUD operations. However, whenever I attempt to update the documents, the following logs are generated: name 1 email 1 mem phone 1jnk bundle.js:1014:13 XMLHttpRequest { readyState: 4, time ...

struggling with installing npm package dependencies

My main objective is to integrate grunt-html-validation into my project, and my general goal is to understand how to enforce npm package dependencies installation. I embarked on this journey due to encountering high-risk errors when running npm audit relat ...