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

Is there a way to display a message in a div container instead of using the alert box when there is a successful ajax response?

Hey there, I'm currently working on implementing error validation handling for a custom form that I've created. I'm looking to display the error messages in a designated div rather than using the standard browser alert box. Since I'm fa ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

Vue displays error logs within Karma, however, the test failure is not being reflected in the Karma results

Currently, I am in the process of writing unit tests for Vue components within our new project. For testing, I am utilizing Karma with Mocha + Chai, and PhantomJS as the browser. The test command being used is cross-env BABEL_ENV=test karma start client/ ...

PHP session gets lost when updated via Ajax calls

Recently, I've encountered an issue where my PHP Session seems to be getting lost after updating the last request time via Ajax while typing in a text editor on my website. The concept is simple - whenever a user interacts with the text editor, I aim ...

What could be causing the issue where only the latest data is being shown

When I use ajax to retrieve data from my database, the console.log displays all the results correctly, but in my HTML, only the last result is shown. What could be causing this issue? Any help would be appreciated! Thanks! Please keep your response simple ...

State is not currently utilizing the variable

const DonorsTables = () =>{ const [search, setSearch] = useState(""); const [countries, setCountries] = useState([]); const [filteredcountries, setFilteredCountries] = useState([]); const getCountries = async () => { try { ...

What is the best way to send JSON data to a code behind method instead of a Webmethod?

I have a dilemma with handling JSON data in my code behind to bind it to an obout grid. While I am aware of passing data using the <WebMethod>, I've encountered limitations as the method is static, making it difficult to bind the data to any gri ...

Trouble with linkage in jQuery for AJAX requests in an external .js document

My asp.net application has a master file that includes the jquery.js file. On another page that uses this master page, I have my own jquery code. I attempted to move this code to an external file and then include it in my .aspx file. While most functions ...

Tips for resolving the error message "cannot find module './node'" when compiling with pkg:

After successfully running my Node.js script with 'node main.js', I encountered an error when trying to compile it into an executable using pkg: pkg/prelude/bootstrap.js:1876 throw error; ^ Error: Cannot find module './node' Require s ...

Determine the number of properties present in two arrays by comparing them

Looking to compare two arrays and determine the count of items in the master list. A sample master list could be: { name: 'Emily', age: 29 }, { name: 'Jack', age: 31 }, { name: 'Lily', age: 28 }, { name: 'Emily', a ...

Managing date validation for a three-part field using AngularJS

I am currently working on validating a three-part date field using AngularJS. I have managed to create a custom validation function, but I am struggling with determining how the fields should update each other's status. How can I ensure that all thre ...

Switching from file:// to http:// in Angular / Ionic is a necessary step when incorporating external scripts like the Disqus directive into your project

Currently, I am attempting to incorporate the disqus directive into my project. The documentation for this directive can be found here. However, I have encountered some issues due to the particular setup of my application. There is a line in the script wh ...

I am currently experiencing difficulties with uploading an image from the admin panel in Magento 1.9. Instead of receiving the expected response, I am

I encountered an error while trying to upload a file in Magento for a product image. When I click on upload, an error is displayed during the file upload process. Upon further investigation in the product.js file for item response, I noticed that HTML is b ...

Create a file by generating JSON data in an ASP.NET MVC post controller and then return the file

I am currently working on an ajax post request: function downloadElevationMap() { var jsonData = ko.toJSON(mod.SelectedItem); $.ajax({ url: '/Home/GetData/', type: 'POST', contentType: "application/jso ...

Accessing the path to an imported file in Node.js

Currently, I am working on a parser and encountering imports such as ../modules/greeting.js. Additionally, I have an absolute path to the file from where I performed the import: C:\Desktop\Folder\src\scripts\main.js. I am seeking ...

Getting a URL path in Next.js without relying on the Link component when the basePath is configured

Base Path from the next.js documentation states: For instance, by setting basePath to /docs, /about will automatically transform into /docs/about. export default function HomePage() { return ( <> <Link href="/about"> ...

Create a form in a PHP file containing a pair of buttons for selecting a specific action

Consider the following HTML code snippet: <body onload="showcontent()"> <!-- onload attribute is optional --> <div id="content"><img src="loading.gif"></div> <!-- exclude img tag if not using onload --> < ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

angularjs determining the appropriate time to utilize a directive

I have been delving into JavaScript and AngularJS for approximately a month now, but I still find myself unsure of when to use directives. For example: I am looking to display appointments in a table with the date as the table header. I envision having bu ...

Toggle the play/pause function by clicking - Trigger Ajax

I have a campaign that can be either played or paused. Currently, I have implemented the pause feature using AJAX and now I need to add the play feature as well. When I click on the pause button, I want it to be replaced with the play button. This is the ...