mohamed sahleya
mohamed sahleya

Reputation: 1

Uncaught ReferenceError: addToCart is not defined javascript

i am using javascript onclick function to make a function but it returns an error Uncaught ReferenceError: addToCart is not defined i don't know why here is my code

my javascript code

function addToCart(){
  var productname = $('pname').text();
  var productid = $('productid').text();
  var color = $('#color option:selected').text();
  var color = $('#size option:selected').text();
  var quantity = $('#qty').val();
  $.ajax({
    type: "POST",
    dataType: 'json',
    data:{
      color:color,
      size:size,
      quantity:quantity,
      productname:productname,
    },
    url: "cart/data/store"+productid,
    success:function(data)
    console.log(data);
  })

and my onclick input

<input type="submit" class="btn btn-primary" onclick="addToCart()" value="add to cart">

Upvotes: 0

Views: 972

Answers (4)

h-sifat
h-sifat

Reputation: 1585

I think your addToCart function is either not loading or not defined in the global scope!

Example 1 (Function defined in global scope)

function hi() {
  alert("hi");
}
<button onclick="hi()">Click Me</button>

Example 2 (onClick function not defined in global scope)

(() => {
  function hi() {
    alert("hi");
  }
})()
<button onclick="hi()">Click Me</button>

Upvotes: 0

Who Do You think am i
Who Do You think am i

Reputation: 455

In the case of everything is okay then what you can do is insted of onclick in html

<input type="submit" class="btn btn-primary" id="cart-btn" value="add to cart">

Script:

 $(document).ready(function(){
   function addToCart(){
   //function definition
 }
  $("#cart-btn").click(addToCart);
 });

Upvotes: 0

Noah
Noah

Reputation: 514

This is probably happening because the browser isn't properly loading your function. I would try adding a console.log above and outside of your function definition to make sure it's being loaded.

More generally, if you're using jQuery, you probably want to attach that addToCart onclick handler in Javascript rather than in HTML. See this question for more details: Add onclick event to button after document is ready with JS/JQuery selecting by class

Upvotes: 0

Umut Ger&#231;ek
Umut Ger&#231;ek

Reputation: 1046

You did onclick="addToCart()" which immediately executed the function you should onclick="addToCart".

Upvotes: 1

Related Questions