Skip to content

Ajax post with CSRF-TOKEN? #154

@githubwyllie

Description

@githubwyllie

How can I append the ajax property an headers for an X-CSRF-TOKEN?


const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                        
const el = document.getElementById('h5p-container');
const options = {
                            h5pJsonPath: 'h5p-content/true-false-question-34806/',
                            frameJs: 'h5p/frame.bundle.js',
                            frameCss: 'h5p/styles/h5p.css',
                            postUserStatistics: true,
                            ajax: {
                                setFinishedUrl: "{{ route('h5p.finish') }}",

                                // THIS DOES NOT WORK 
                                headers: {
                                    'X-CSRF-TOKEN': csrfToken, // Use the fetched CSRF token here
                                    '_method': 'patch',
                                },

                            },
                        };                        
new H5PStandalone.H5P(el, options);

For testing this workarround worked for me in Laravel:

<script>
                        $.ajax({
                            url: "{{ route('h5p.finish') }}",
                            type: 'POST', 
                            data: {
                                contentId: 'lykvh3vvf',
                                score: 1,
                                maxScore: 1,
                                opened: 1710971851,
                                finished: 1710971854
                            },

                            // THIS WORK 
                                headers: {
                                    'X-CSRF-TOKEN': csrfToken, // Use the fetched CSRF token here
                                    '_method': 'patch',
                                },

                        });
 </script>

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions