Issues with integrating chart.js in Laravel 7: Element #app not found?

Currently, I am utilizing chart.js to display the statistics of reviews and messages for a user. However, I have encountered issues with the scripts. While the stats are functioning correctly, an error message stating Cannot find element: #app is appearing, and I am unsure of how to address this.

If I include defer in this script (although I removed it to observe the stats working, which disrupted the rest of the website)

<script src="{{ asset('js/app.js') }}"></script>

The stats stop working, and another error surfaces, such as Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side effects in your templates, such as , as they will not be parsed.

Thus, using defer causes errors, while excluding defer results in the inability to locate #app.

What steps should I take next? Your assistance is greatly appreciated!

The content of my app.blade.php file (where the previous script is located)

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    {{-- <title>{{ config("app.name", "Bool n Roll") }}</title> --}}
    <title>Bool 'n' Roll</title>

    <script src="{{ asset('js/app.js') }}"></script>

    ...

</body>
</html>

My stat view The challenge might lie here. Are the scripts structured incorrectly? Is there a better way to integrate them into the workflow?

@extends('layouts.app')

@section('content')
...

@endsection

The app.js file This section might contain the issue. I attempted to encapsulate the Vue instance within an addEventListener('load') or similar approach to delay loading the instance, but it did not yield the desired outcome.

require('./bootstrap');

window.Vue = require('vue');

import router from './router';

var dayjs = require('dayjs')
// dayjs().format()

...

The StatController Everything seems fine here. I am providing this information to give you a complete overview of the process involved in obtaining the statistics for reviews and messages of a user.

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

...
        
class StatController extends Controller
{
    
    public function showStats(){

        ...

        return view('admin.musicians.stats', compact('musician', 'messages', 'reviews'));
    }
}

Answer №1

Enhance your app.blade.php file by relocating the line

<script src="{{ asset('js/app.js') }}"></script>
from the header to the body section after the footer.

...

<script src="{{ asset('js/app.js') }}"></script>

@yield('script')
    
</body>
</html>

To add additional scripts after 'app.js', introduce @stack('script') and update your My Stat View accordingly:

@extends('layouts.app')

@section('content')
<div class="my_container">
  <h1 class="stat_title">Your Statistics</h1>
  @if (count($messages) == 0 && count($reviews) == 0)
      <h2 id="empty_page">You have no available statistics</h2>
  @else

  <div class="chart_1">
    <h4>Number of messages and reviews received each month</h4>
    <canvas id="myChart"></canvas>
  </div>
  <div class="chart_1">
    <h4>Ratings received each month</h4>
    <canvas id="myOtherChart"></canvas>
  </div>
  @endif
  <p class="link_dashboard"><a href="{{ route('admin.welcome') }}">Back to Dashboard</a></p>
</div>
@endsection

@push('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js" integrity="sha512-Wt1bJGtlnMtGP0dqNFH1xlkLBNpEodaiQ8ZN5JLA5wpc1sUlk/O5uuOMNgvzddzkpvZ9GLyYNa8w2s7rqiTk5Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.6/dayjs.min.js" integrity="sha512-bwD3VD/j6ypSSnyjuaURidZksoVx3L1RPvTkleC48SbHCZsemT3VKMD39KknPnH728LLXVMTisESIBOAb5/W0Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


<script>dayjs().format()</script>


<script>

  dayjs().format()
var ctx = document.getElementById('myChart');
var ct2 = document.getElementById('myOtherChart');
var comments = {!! $reviews->toJson() !!};
var messages = {!! $messages->toJson() !!};
// Rest of existing script code...</exanswer1>
<div class="answer accepted" i="69140363" l="4.0" c="1631328208" a="UyBOIFNoYXJtYQ==" ai="10063903">
<p>Update you <code>app.blade.php. Remove this <script src="{{ asset('js/app.js') }}"></script> from header and put in body after footer.

...

<script src="{{ asset('js/app.js') }}"></script>

@yield('script')
    
</body>
</html>

Then use @stack('script') to load other script after app.js, update your My Stat View

@extends('layouts.app')

@section('content')
<div class="my_container">
  <h1 class="stat_title">Le tue statistiche</h1>
  @if (count($messages) == 0 && count($reviews) == 0)
      <h2 id="empty_page">Non hai statistiche disponibili</h2>
  @else

  <div class="chart_1">
    <h4>Numero di messaggi e recensioni ricevute ogni mese</h4>
    <canvas id="myChart"></canvas>
  </div>
  <div class="chart_1">
    <h4>Voti ricevuti ogni mese</h4>
    <canvas id="myOtherChart"></canvas>
  </div>
  @endif
  <p class="link_dashboard"><a href="{{ route('admin.welcome') }}">Torna alla Dashboard</a></p>
</div>
@endsection

@push('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js" integrity="sha512-Wt1bJGtlnMtGP0dqNFH1xlkLBNpEodaiQ8ZN5JLA5wpc1sUlk/O5uuOMNgvzddzkpvZ9GLyYNa8w2s7rqiTk5Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.6/dayjs.min.js" integrity="sha512-bwD3VD/j6ypSSnyjuaURidZksoVx3L1RPvTkleC48SbHCZsemT3VKMD39KknPnH728LLXVMTisESIBOAb5/W0Q==" crossorigin="anonymous" referrerpolicy="no-refreferrer"></script>


<script>dayjs().format()</script>


<script>

  dayjs().format()
var ctx = document.getElementById('myChart');
var ct2 = document.getElementById('myOtherChart');
var commenti = {!! $reviews->toJson() !!};
var messaggi = {!! $messages->toJson() !!};
// console.log(commenti.length);
// console.log(messaggi.length);
var now = dayjs();
if (commenti[0]) {
  var primaDataCommento = commenti[0].created_at;
  var date1 = dayjs(primaDataCommento);
} else {
  var date1 = now;
}
const primaDataMessaggio = messaggi[0].created_at;
const date2 = dayjs(primaDataMessaggio);
var datex;
if (date2 < date1) {
  datex = date2;
} else {
  datex = date1;
}
var diff = now.diff(datex, 'month');
var diffRece = now.diff(date1, 'month');
var months = [];
var monthsRece = [];
var recensioniMese = [];
var messaggiMese = [];
var voto1 = [];
var voto2 = [];
var voto3 = [];
var voto4 = [];
var voto5 = [];
// First table
var x = 1;
let i = 0;
if (datex.$M == 0) {
  diff++;
  i++;
  x--;
}
for (i; i <= diff; i++) {
  var numeroMese = datex.$M + i + x;
  months.push(numeroMese + '/2021');
  var countRec = 0;
  var countMes = 0;
  for (let j = 0; j < commenti.length; j++) {
    if (numeroMese == dayjs(commenti[j].added_on).$M + 1) {
      countRec++;
    }
  }
  for (let j = 0; j < messaggi.length; j++) {
    if (numeroMese == dayjs(messaggi[j].added_on).$M + 1) {
      countMes++;
   }
  }
  recensioniMese.push(countRec);
  messaggiMese.push(countMes);
}
// Second table
x = 1;
i = 0;
if (date1.$M == 0) {
  diffRece++;
  i++;
  x--;
}
for (i; i <= diff; i++) {
  var numeroMeseRece = date1.$M + i + x;
  monthsRece.push(numeroMeseRece + '/2021');
  var countRece1 = 0;
  var countRece2 = 0;
  var countRece3 = 0;
  var countRece4 = 0;
  var countRece5 = 0;
  for (let j = 0; j < commenti.length; j++) {
    if (numeroMeseRece == dayjs(commenti[j].created_at).$M + 1) {
      switch (commenti[j].vote) {
        case 1:
          countRece1++;
          break;
        case 2:
          countRece2++;
          break;
        case 3:
          countRece3++;
          break;
        case 4:
          countRece4++;
          break;
        case 5:
          countRece5++;
          break;
        default:
          break;
      }
    }
  }
  voto1.push(countRece1);
  voto2.push(countRece2);
  voto3.push(countRece3);
  voto4.push(countRece4);
  voto5.push(countRece5);
}
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: months,
        datasets: [
          {
            label: 'Numero di recensioni',
            data: recensioniMese,
            backgroundColor: [
                '#0000ff8c',
            ],
            borderColor: [
                '#0000ff',
            ],
            borderWidth: 1
        },
        {
            label: 'Numero di messaggi ricevuti',
            data: messaggiMese,
            backgroundColor: [
                '#ff00c88c',
            ],
            borderColor: [
                '#ff00c8',
            ],
            borderWidth: 1
        },
      ]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                stepSize: 1
              }
            }
        }
    }
});
var myChart = new Chart(ct2, {
    type: 'bar',
    data: {
        labels: monthsRece,
        datasets: [
          {
            label: 'Recensioni con voto 1',
            data: voto1,
            backgroundColor: [
                '#ff00008c',
            ],
            borderColor: [
                'red',
            ],
            borderWidth: 1
        },
        {
            label: 'Recensioni con voto 2',
            data: voto2,
            backgroundColor: [
                '#ffa6008c',
            ],
            borderColor: [
                'orange',
            ],
            borderWidth: 1
        },
        {
            label: 'Recensioni con voto 3',
            data: voto3,
            backgroundColor: [
                '#ffff008c',
            ],
            borderColor: [
                'yellow',
            ],
            borderWidth: 1
        },
        {
            label: 'Recensioni con voto 4',
            data: voto4,
            backgroundColor: [
                '#b7dd298c',
            ],
            borderColor: [
                '#b7dd29',
            ],
            borderWidth: 1
        },
        {
            label: 'Recensioni con voto 5',
            data: voto5,
            backgroundColor: [
                '#57e32c8c',
            ],
            borderColor: [
                '#57e32c',
            ],
            borderWidth: 1
        },
      ]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                stepSize: 1
              }
            }
        }
    }
});
</script>
@endpush

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

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

A step-by-step guide on including chess.js in your Create React App

I'm facing an issue while trying to incorporate the chess.js npm library into my Create React App. The error message "Chess is not a constructor" keeps popping up. Below is the code snippet I am using: import React from 'react'; import &apos ...

What could be causing the malfunction of material-UI Tabs?

My Material UI Tabs seem to have stopped working after a recent update. I suspect it may be related to the react-tap-event-plugin update I installed. Initially, I thought it was due to tab indexing but even using values like value='a', value=&apo ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Tips for converting Form Input field data into JSON Format with Jquery Ajax

I need to convert data from the controller into JSON format, but it is currently in string form. Is there a way to achieve this? I tried using headers for passing data in an AJAX call, but it doesn't convert the form field into JSON format. Due to the ...

Chrome runs requestAnimFrame at a smooth 60 frames per second, while Firefox struggles to keep up at

I recently developed a canvas animation using requestAnimFrame and saw great results in Chrome. However, when I viewed it in Firefox, it seemed like a slideshow was running instead of a smooth animation. I'm unsure what could be causing this issue. F ...

Using Jquery to retrieve data in sections from a server and continuously add it to a file on the client side

I have a large dataset stored in JSON format on a Postgres Server with hundreds of thousands of rows. To prevent memory overload on the server, I need to provide users with the ability to download the data in chunks rather than all at once. This requires a ...

Using JQuery to rebind() after resetting the count

In my game, I have implemented a feature to ensure that the start button can only be clicked once each time it appears in order to prevent the function from loading multiple times. I wrote some code that tracks the number of clicks and unbinds the click e ...

Encountered a SyntaxError: Unexpected token "e" while attempting to parse a JSON string

When I attempt to use JSON.parse in order to convert the string below into a JavaScript object, I encounter an "Uncaught SyntaxError: Unexpected token e" error. { "__type": "HRIS.oHRData, HRIES, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ...

Are there advantages to incorporating d3.js through npm in an Angular 2 TypeScript project?

Summary: It is recommended to install d3.js via npm along with the typings. The accepted answer provides more details on this issue. This question was asked during my initial stages of learning Angular. The npm process is commonly used for tree-shaking, pa ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

What might be causing the 500 internal error in jquery.min?

Hello, I am encountering a 500 internal server error when I click this button that performs the following action: $(".btn-email").on('click', function() { swal('Waiting','Please wait, sending email now','info'); ...

Obtain the contenteditable span's value

I'm facing an issue with a content editable span - I want to extract its value when the post button is clicked, but it's not working as expected. Please note that I am unable to convert the span to a textbox or div, I specifically need the value ...

Updating Angular 8 Component and invoking ngOninit

Within my main component, I have 2 nested components. Each of these components contain forms with input fields and span elements. Users can edit the form by clicking on an edit button, or cancel the editing process using a cancel button. However, I need to ...

"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js? App.js import Main from ...

Proper Usage of Vue3 with Vue Router

Trying out Vue3 has been a bit challenging for me. The router setup is custom to my needs. import router from './router' When I include the router like this: createApp(App).use(Antd,VueAxios,axios,qs,router).mount('#app') The page fa ...

Tips for transferring information from a child component to its parent using a click event in the parent component

My React application is designed to generate quizzes. The main component, <CreateQuiz/>, contains a child component called <QuestionForm/>. Additionally, within the <CreateQuiz/> component, there is a button labeled "Add Question" which a ...

Trouble with $sce in Angular.js causing limitations on passing desired content into my directive

I've successfully developed a directive that animates a PNG Sequence. Everything functions perfectly when I manually input the image url, but when attempting to pass a dynamic url, I encounter an error related to $sce disallowing it. Below is the cod ...