Search code examples
javascriptajaxprototype-pattern

JavaScript pattern showing not a function error


I'm new to javascript. I am trying to work with JavaScript pattern. I understood concepts well. But I have no idea how to call the function already in the object.

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

cart.prototype ={   
ajax : function(obj,Url){
    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);
            cart.run();
        },
        error : function() {
          alert('Error while request..');
        }
    });
},
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("into run");
            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("into call function");
     var cartDetails = new cart();
     cartDetails.ajax("","myCart");
}

For clarification :

-I have 3 ajax calls For Remove , Delivery , Also for the page loading

In the Run method I'm creating a DOM table. When the user press remove button Remove method should be called. And the ajax call should work.

But its showing --> Uncaught TypeError: cart.run is not a function at Object.success (mycart.jsp:89)

Note : I also tried this.run(); and this.run; with same result .. Thanks !


Solution

  • Because cart is the "class", while cartDetails is the "instance" of that "class". You should execute "run" on the instance and not the class itself, which is why cart.run() will not work. When you use this.run, "this" does not refer to the instance, as the callback passed to the ajax call was not defined as a property of the cart class itself.

    I have not tried this, but I believe the following should work:

    Your ajax function is defined as a property the cart class, so "this" will refer to the instance. At the beginning of the ajax function, store "this" in a variable, which you can then access later in the success callback:

    ajax : function(obj,Url){
    
        var myself = 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);
    
                myself.run();
    
            },
            error : function() {
              alert('Error while request..');
            }
        });
    },