Issue with importing class in Javascript - javascript

I want to use inheritance between classes that are in separate .js (but same folder), but i have this errors
Uncaught SyntaxError: Unexpected identifier
Uncaught ReferenceError: TableWithFunction is not defined
Here goes my code:
// Table.js
export default class Table {
constructor(name, h_cols) {
table_id = name + 'table';
hidden_cols = h_cols;
table = setTable();
}
setTable() {...};
setColumnDefs() {...};
{
// TableWithFunction.js
import Table from 'Table';
class TableWithFunction extends Table {
constructor (name, h_cols) {
super(name, h_cols);
selected_id = name + 'Selected';
}
//More methods ..
}
//test.blade.php (im using laravel framework)
<script src="{{ url('js/TableWithFunction.js') }}" ></script>
<script>
roleTable = new TableWithFunction('role',[2, 4]);
userTable = new TableWithFunction('user',[3]);
</script>
I also tried to do import Table from 'Table.js'; instead of import Table from 'Table';
And i tried changing Table.js using class Table { ... } export default Table instead of export default class Table {...} and it didn't fix it, of course.

To use ES6 modules in a capable browser the importing script needs to be included with type="module".
<script src="{{ url('js/TableWithFunction.js') }}" type="module"></script>
This prevents browsers not ready for modules to load code which would only throw an error.
The opposite is also available:
<script src="only-for-ie.js" nomodule></script>
This script will be ignored by browsers capable of handling ES6 modules.

Related

How to use function in another public js file

I originally had the following code commands for simplicity I put it just below the body in the html file.
This is my code:
<script>
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
async function MyPopUpPost(title,route) {
var a = await Swal.fire({
title: title,
html: '<input id="Result" class="swal2-input" type="text"></input>',
showDenyButton: true,
})
var value = $('#Result').val()
if (a.isConfirmed) $.post(route,{a:value})
}
</script>
It seems that the function MyPopUpPost will be reused many times in other html files and leaving the code here will not be very neat. So, I put it in another file.
This is my code in UtilitiesForm.js:
export async function MyPopUpPost(title, route) {
var a = await Swal.fire({
title: title,
html: '<input id="Result" class="swal2-input" type="text"></input>',
showDenyButton: true,
})
var value = $('#Result').val()
if (a.isConfirmed) $.post(route, {
a: value
})
}
And back to the html file I try import or require to use that function but it is not working:
<script>
import {MyPopUpPost} from '/js/UtilitiesForm.js'
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
</script>
Is there a way to redo the work between public JS files?
You have two options,
You can import your file into the HTML by using the script's src attribute.
Check this out: https://www.w3schools.com/tags/att_script_src.asp
Then, Change your script to the following and you should be ok:
<script src='/js/UtilitiesForm.js'></script>
<script>
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
</script>
add type="module" to your script.
Check this out: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type
It seems you are doing it correct, just mention the type in script tag, make sure your path is correct to the JS file.
<script type="module">
import {MyPopUpPost} from '/js/UtilitiesForm.js'
async function ThemMonHoc() {
MyPopUpPost('Thêm môn học','/ThemMonHoc')
}
async function SuaTen() {
MyPopUpPost('Sửa tên môn học','/SuaTenMonHoc')
}
</script>
I recommend you checking this link, how to import files in HTML.
If you want to use ES6 modules, you need type="module" on your <script> tag.
If you look in your browser's Console, it should probably tell you something to that effect.
But if you don't use ES6 modules, it will actually be simpler; things will be global by default and you don't need any import/export statements, you just include the utilities as a <script> before the main <script> code.
It's up to you which style to use; ES6 modules are cleaner, but require more management.

Embed SharpSpring form into React component

I'm trying to embed a Sharpspring form script into my React (page.jsx) component. For this form to load succesfully it needs to be placed outsite the <head></head> element, and inside the <div> where I want to display the form.
The original HTML code I need to embed looks like this:
<!-- SharpSpring Form -->
<script type="text/javascript">
var ss_form = {'account': 'MzawMDE3tzQzBQ', 'formID': 'szBIMrFMSzbXTUm0TNM1MTc107VMNbfQTTRJTExOTUoySk4zAA'};
ss_form.width = '100%';
ss_form.domain = 'app-3QNK98WC9.marketingautomation.services';
// ss_form.hidden = {'field_id': 'value'}; // Modify this for sending hidden variables, or overriding values
// ss_form.target_id = 'target'; // Optional parameter: forms will be placed inside the element with the specified id
// ss_form.polling = true; // Optional parameter: set to true ONLY if your page loads dynamically and the id needs to be polled continually.
</script>
<script type="text/javascript" src="https://koi-3QNK98WC9.marketingautomation.services/client/form.js?ver=2.0.1"></script>
I'm trying to embed it into page.jsx this way:
import React from "react";
function myComponent() {
var ss_form = {'account': 'MzawMDE3tzQzBQA', 'formID': 'szBIMrFMSzbXTUm0TNM1MTc107VMNbfQTTRJTExOTUoySk4zAAA'};
ss_form.width = '100%';
ss_form.domain = 'app-3QNK98WC9Y.marketingautomation.services';
return (
<main>
<div className="form">
{ss_form}
<script src="https://koi-3QNK98WC9Y.marketingautomation.services/client/form.js?ver=2.0.1" type="text/javascript" />
</div>
</main>
);
}
export default myComponent;
However, I get this error:
Error: Objects are not valid as a React child (found: object with keys {account, formID, width, domain}). If you meant to render a collection of children, use an array instead.
I know I'm supposed to use "arrays instead" but I could not find any documentation that solved this error. Any suggestions on how I could make this embed code to work?
Thank you.
I was able to embed the form using helmet.
First installed:
npm install helmet
My working code looks like this:
import React from "react";
import ReactDOM from "react-dom";
import { Helmet } from 'react-helmet';
function myComponent() {
return (
<main>
<Helmet>
<script
src="https://koi-3QNK98WC9.marketingautomation.services/client/form.js?ver=2.0.1"
/>
<script>
{`
var ss_form = {'account': 'MzawMDE3tzQzBQ', 'formID': 'szBIMrFMSzbXTUm0TNM1MTc107VMNbfQTTRJTExOTUoySk4zAA'};
ss_form.width = '100%';
ss_form.domain = 'app-3QNK98WC9Y.marketingautomation.services';
ss_form.target_id = 'form';
ss_form.polling = true;
`}
</script>
</Helmet>
<div id="form"> </div>
</main>
);
}
export default myComponent;
Turns out SharpSpring embed code supports the variant ss_form.target_id, which displays the form on the designated ID.
I'm sure the above solution will work for other javascripts and embed codes as well.

Script trying to define a function from the wrong file

I want to call a function 'addArray' in a separate .js file called 'main.js'
When I run this code, I get an error saying the 'addArray' is not defined in checkout.js
I don't want it to look for the function in checkout.js, I want it to look for the function in main.js
I am using node.js
<body onload="myFunction()">
<script src = "https://www.paypalobjects.com/api/checkout.js"></script>
<script type = "text/javascript" src = "main.js"></script>
<div class="container">
</div>
<script>
paypal.Button.render(
{
onAuthorize: function(data, actions)
{
return actions.payment.execute().then(function()
{
// Show a confirmation message to the buyer
days = 30
localStorage.setItem("days", days);
inputDays = JSON.parse(localStorage.getItem('days'));
inputName = localStorage.getItem('name');
window.alert('Thank you for your purchase!');
console.log(inputDays);
console.log(inputName);
addArray();
});
}
}, '#paypal-button');
I had to delete most of the intermediate non essential code for the purpose of submitting this question
So... There are a few things I think you should check for.
If you are using commonJS, be sure that you are exporting the addArray function like so: module.exports = {addArray}; Then require it from your main.js file.
If you are using es6 syntax, you can export it like export default addArray or export {addArray}, then import it in your main.js file using the import {addArray} from... or import addArray from ... depending on the export style you used.

Import and export issue Javascript (No node.js)

Hello !
I tried using import/exports for the first time, and I have this issue in my code :
The requested module '../Ajout/script.js' does not provide an export named 'flagMap'
I have these files Supprimer.js, containing at the first line :
import{flagMap, findUrl, createUrl,texteValide} from '../Ajout/script.js';
And in Ajout.js contained in another forlder in the parent folder:
var flagMap={/*really long map*/}
function findUrl(isoCode){/*long url finder*/}
function createUrl(svgUrl) {
return `https://upload.wikimedia.org/wikipedia/${svgUrl}`;
}
function texteValide(element){/*text validation for a form*/}
export{flagMap,findUrl,createUrl,texteValide};
/*
other non-exported functions
*/
There is the type="module" in my html when I'm importing the script, and my Ajout.js also contains other functions, maybe it's causing issues ?
Also : The issue is not only flagMap but every import, because it shows another file if I remove flagMap from the imports
This works fine for me:
<!-- index.html -->
<html>
<head> ... </head>
<body>
<script type="module" src="path/to/Supprimer.js"></script>
</body>
</html>
// Ajout.js
var flagMap = {
// ...
};
function findUrl(isoCode) {
// ...
}
function createUrl(svgUrl) {
// ...
}
function textValide(element) {
// ...
}
// Export functions and variables
export {
flagMap,
findUrl,
createUrl,
texteValide
};
// Supprimer.js
import { flagMap, findUrl } from "path/to/Ajouter.js";
console.log(flagMap); // Prints map
findUrl("EN"); // Can call function

Why isn't html running javascript I import when I use import-export

My code works fine when I add my module straight into the html code, but it won't load it when I try to first import the module to a different javascript file.
I've tried exporting everything, from my module.
HTML:
<html>
<head>
<title>
Hello world
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Tradingpost, done by no css gang.</h1>
<div id="sidenav">Here be the links to other pages</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script src="js/app.js"></script>
</body>
</html>
app.js:
import * as sidebar from "./visualModules/sidebarmodule"
function cumulator() {
sidebar.createSidebar()
}
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
It should add elements to the div. But it wont do it unless I straight up use the sidebarmodule.js. I want to do it through the app.js
EDIT
Found the problem!
Didn't initialize index in the for loop.
EDIT2
And the type="module" which needed to be added
When you load your app.js in your html file, try to add:
<script type="module" src="js/app.js"></script>
That should work when you want to use ESModules. But please update us regardless :)
Update:
Ok after creating a project myself using your HTML and JS, I found a few errors.
First: When using ESModules, you can't use any functions in the JS through your HTML, you will have to inject everything from the app.js.
index.html:
<body>
<div id="sidenav">
Here be the links to other pages
</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script type="module" src="js/app.js"></script>
app.js:
import { createSidebar } from './visualModules/sidebarmodule.js';
cumulator();
function cumulator() {
createSidebar()
}
Notice two things: at the end of the import, since we are not using a compiler, the modules do not recognize files without their extension. So I had to add .js to sidebarmodule. Secondly, I had to invoke cumulator function within the app.js file (like I said earlier, you cannot use any module functions outside their scope. There are no global variables with ESModules).
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(var index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
You did not declare index inside your for loop, so I just added a var.
Hope this helps.
import is asynchronous in Javascript (in a browser, not Node.js) so you're calling createSidebar() before the module is loaded. You can use import to return a promise so you can execute code once it is completed.
Remove the embedded Javascript from your html, but leave the link to app.js. Then change app.js to this...
import("./visualModules/sidebarmodule")
.then((sidebar) => {
sidebar.createSidebar();
});

Categories