Home > Back-end >  Uncaught ReferenceError: buyNft is not defined at HTMLAnchorElement.onclick
Uncaught ReferenceError: buyNft is not defined at HTMLAnchorElement.onclick

Time:07-11

Am I missing to add some script or what? I am getting error from title. How can I solve this, if you can help me, I would be grateful. I tried adding different scripts, but I amgetting the same error.

 <a onclick="buyNft({{$nft->id}})">{{trans('nft.buy')}}</a>
    
        @push('scripts')
            <script>
        
                function buyNft(nftid) {
                    swal({
                        title: "Are You Sure?",
                        text: "Do you want to buy this nft?",
                        type: 'warning',
                        showCancelButton: true,
                        showConfirmButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
        
        
                    }).then((result) => {
                        if (result) {
                            axios.post("/buythisnft/"   nftid).then(response => {
                                window.location.reload();
                            });
        
                        }
                    });
        
                }
            </script>
        @endpush

CodePudding user response:

Your buyNft-function needs to be declared BEFORE you echo out any element with "onclick=buyNft()":

@push('scripts')
  <script>
      function buyNft(nftid) {
          // ...
      }
  </script>
@endpush
 
 <a onclick="buyNft({{$nft->id}})">{{trans('nft.buy')}}</a>

UPDATE: This is an example using a script at the bottom of the page which creates an eventlistener for click-events:

document.addEventListener("click",e => {
  if(e.target.closest(".buyNft")){
    e.preventDefault();

    alert("You want to buy an NFT.")
    
    //... Replace with your own functions ...
  }
})
<a  href="#">Buy that NFT</a>
<br /><br />
<a href="#">Some other link on this page</a>

  • Related