Script trying to define a function from the wrong file - javascript

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.

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.

correct javasript code execution in flask

I tried to use click on button:
#app.route("/")
def test_edition_open():
return render_template("index.html")
my index.html file is:
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
The main part is just two buttons:
<div class = "counter">
<button class = "minus">-</button>
<div class = "result">1</div>
<button class = "plus">+</button>
</div>
I tried to make My script.js file work in flask. The code is very simple, it should add numbers by clicking on button:
const plus = document.querySelectorAll('.plus');
const minus = document.querySelectorAll('.minus');
const result = document.querySelectorAll('.result');
function min()
{
return function (ev)
{
if (ev.target.nextElementSibling.innerHTML > 0)
{
return --ev.target.nextElementSibling.innerHTML;
}
}
}
function pl()
{
return function (ev)
{
return ++ev.target.previousElementSibling.innerHTML;
}
}
minus.forEach(function (dominus)
{
dominus.addEventListener('click', min());
})
plus.forEach(function (doplus)
{
doplus.addEventListener('click', pl());
})
In https://playcode.io this code worked well. How should I solve this problem?
Make sure that script file successfully connected to html file. to check this add console.log("File Connected") in your script.js file. Then open your browser console to check that console message is logged correctly. If not then try to linked your static file correctly. How to set static_url_path in Flask application
Or you can put your Javascript code in html file using script tag.
Something like this:
<script> your javascript code here</script>

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

Issue with importing class in 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.

Categories