JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object.

  var productValues = 0;
  var cart = function(){ 
  this.method = "get";
  } 

cart.prototype ={   
ajax : function(obj,Url){
    console.log("Making an ajax call");
    $.ajax({
        url: Url,
        type :"Get",
        headers : {
            'Accept':'Application/json',
            'Content-Type' : 'Application/json'
        },
        data :  "jsonObj="+JSON.stringify(obj),
        success : function(response) {
            productValues= response;
            console.log(productValues);
            cart.run();
        },
        error : function() {
          alert('Error while requesting..');
        }
    });
},
remove : function(number){
     var obj={"identity": number };
     this.ajax(obj,"Cartremove");
     window.location.href="mycart.jsp";
},

delivery : function(number){
     var obj={"identity": number };
     this.ajax(obj,"delivery");
     window.location.href="delivery.jsp";
},

run : function(){
    console.log("Running process...");
            var count=1;
            if(typeof productValues.obj1 === "undefined"){
                var h3 = document.createElement('h3');
                var t1 =document.createTextNode("Nothing to display");
                h3.appendChild(t1);
                h3.setAttribute("align","center");
                document.getElementById("addtable").appendChild(h3);
            }
            else{
             $.each(productValues, function (index, value) {
                    var cell, row, table;
                    table = document.createElement('table');
                    table.setAttribute('align','center');
                    table.style.width= '60%';
                    table.style.cellpadding ="19px";

                    table.setAttribute("class","table table-bordered");
                    row = table.insertRow(0); 
                    row.setAttribute('align','center');
                    var x= row.insertCell(0);x.innerHTML = "Type";
                    x.style.color="white";
                    var y= row.insertCell(1);
                    y.innerHTML = "Description";
                    y.style.color="white";
                    row.style.backgroundColor ="#006064";
                    row = table.insertRow(1); row.setAttribute('align','center');
                    var prod=  row.insertCell(0); prod.innerHTML = "ProductName";
                    prod.setAttribute("value",value.id);
                    prod.setAttribute("id","nn");
                    row.insertCell(1).innerHTML = value.productname;

                    row = table.insertRow(2); row.setAttribute('align','center');
                    row.insertCell(0).innerHTML = "Price";
                    row.insertCell(1).innerHTML = value.price;

                    row = table.insertRow(3); row.setAttribute('align','center');
                    row.insertCell(0).innerHTML = "Quantity";
                    row.insertCell(1).innerHTML = value.quantity;

                    row = table.insertRow(4); row.setAttribute('align','center');
                    row.insertCell(0).innerHTML = "Discount";
                    row.insertCell(1).innerHTML = value.discount;
                    var br =document.createElement("br");
                    var add= document.getElementById("addtable");
                    add.setAttribute("align","center");
                    add.appendChild(br);
                    add.appendChild(br);
                    add.appendChild(table);
                    var buyBtn = document.createElement("Button");
                    buyBtn.setAttribute("class","btn btn-primary");
                    buyBtn.innerHTML="Buy";
                    buyBtn.setAttribute("value",count);
                    buyBtn.setAttribute("id","deliveryBtn");
        buyBtn.addEventListener("click",function(){this.delivery(value.id);});
                    add.appendChild(buyBtn);

                    var removeBtn = document.createElement("Button");
                    removeBtn.setAttribute("class","btn btn-primary");
                    removeBtn.innerHTML="remove";
                    removeBtn.setAttribute("id","removeBtn");
                    removeBtn.setAttribute("value",count);
         removeBtn.addEventListener("click",function(){this.remove(value.id);});
                    add.appendChild(removeBtn);
                    var div =document.createElement("div");
                    var linebreak= document.createElement("br");
                    div.appendChild(linebreak);
                    add.appendChild(div);
                    count++;
          });
         }
         }
}
function call(){
    console.log("Initiating call function");
     var cartDetails = new cart();
     cartDetails.ajax("","myCart");
}

For further clarification:

-I have three separate ajax calls for Remove, Delivery, and page loading purposes.

Within the Run method, a DOM table is being created. When the user clicks on the remove button, the Remove method should be invoked, triggering an ajax call.

However, an error is displayed as follows: Uncaught TypeError: cart.run is not a function at Object.success (mycart.jsp:89)

Note : I have also tried using this.run(); and this.run; with the same outcome. Thank you!

Answer №1

When working with classes and instances, it's important to remember that the instance should execute certain methods, not the class itself. In this case, the 'cart' is the class, while 'cartDetails' is an instance of that class. Therefore, calling 'cart.run()' will not work because you should be executing 'run' on the instance ('this') instead of the class.

To make it work, you can store a reference to 'this' in a variable at the beginning of your ajax function. This way, inside the success callback, you can access the instance using the variable:

ajax : function(obj,Url){

    var self = this;

    console.log("into ajax call");
    $.ajax({
        url: Url,
        type :"Get",
        headers : {
            'Accept':'Application/json',
            'Content-Type' : 'Application/json'
        },
        data :  "jsonObj="+JSON.stringify(obj),
        success : function(response) {
            productValues= response;
            console.log(productValues);

            self.run();

        },
        error : function() {
          alert('Error while request..');
        }
    });
},

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

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

Using Ajax to call a PHP function within a WordPress website

I am looking to trigger a PHP function using AJAX. Below is the code snippet of my form: <form class="woocommerce-form woocommerce-form-login login" method="post"> <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-ro ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Implementing Autocomplete Functionality with Symfony3 Using AJAX and Chosen2

Hello there and thank you for assisting me. English is not my mother language, so please bear with me. :) Whenever I choose an item from the selectbox, I am greeted with a "no results found" message. However, upon inspecting the developer toolbar, I notic ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

Transfer data between PHP files seamlessly using Jquery

I need help passing a variable from file1.php to file2.php using jQuery. file1.php <?php $user_rank = $rank; ?> file2.php <?php $user_rank = $_GET['user_rank']; ?> AJAX function getRank() { $.ajax({ type: "GET", ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Using ReactJS to transform my unique array into an object before appending it to a list

Here is the array I am working with: [{…}] 0: {id: 2, createdAt: "2021-06-11T10:13:46.814Z", exchangedAt: "2021-06-11T08:04:11.415Z", imageUrl: "url", user: "user", …} 1: .... 2: .... 3: .... .... length: 5 __pro ...

Testing if the App properly renders results in an error message: "No element found with the text: Profil"

I am struggling with testing Jest as I lack experience in this area. Specifically, I need to determine whether the App component is being rendered successfully. However, my test cases are failing. Upon checking the console log, I encountered the following ...

Unable to process JSON data object

Having trouble with processing a json object. The form on the page contains a dropdown where selecting a truck number should autofill the rest of the form with data from a json file. Sample data: [ { "truckNum":"62-559", "description":"MOF ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

Is there a difference in performance between using multiple inline scripts versus one combined inline script?

Comparing Multiple Inline Scripts to a Single Conjoined Inline Script: <script type="text/javascript">/* some codeblock 1 */</script> <script type="text/javascript">/* some codeblock 2 */</script> <script type="text/javascript"& ...

Enhance user interface dynamically with additional components in ReactJS by rendering them onClick. Master the optimal

Just started using React and I'm really enjoying it. I have a scenario where the parent component renders both: A TagBuilderContainer (which contains initially 1 TagBuilderComponent) An "Add Tag" button with an onClick event (intended to add a new ...

Encountered an error while attempting to access property 'someProperty' of an undefined value in a React application

Currently, I am developing an application that involves passing variable values within a Navlink using state from one component to another. Once the values are received, they need to be loaded into input fields and then upon clicking the submit button in t ...

Manipulating JSON with ng-model in AngularJS

Let's say I have a simple JSON similar to this: { "Object 0": {} } I am trying to display it as a tree structure. This is the approach I am taking: <span>{{key}}</span> // Object 0 <span>{{value}}</span> // {} <ul> ...

Error message in Node.js with Multer: The function '.array' is not recognized

I've spent the last two days searching for a solution to this issue, but the only reference I could find was an unresolved problem reported on version 1.1.0: https://github.com/expressjs/multer/issues/338 I am using the Node.js SDK and Express framew ...

Is your Firebase .push() function encountering errors when trying to update the database?

I am facing an issue with a component that checks if a user has already upvoted a post. The logic is such that if the user has upvoted a post before, they cannot upvote it again. However, if they haven't upvoted it yet, they should be able to do so. ...

VueJS with Vuetify: Issue with draggable cards in a responsive grid

I am currently working on creating a gallery that allows users to rearrange images. To test this functionality, I am using an array of numbers. It is important that the gallery is responsive and displays as a single column on mobile devices. The issue I ...