Making live python compiler inside a HTML page using PyScript - javascript

I want to build a live Pythonn compiler similar to those at w3schools for Python, for some examples on my blog. I tried different approaches, and would like to hear different oppinions, but as of yesterday I'm trying to implement it using PyScript.
The documentation I found for PyScript doesn't help me a lot, as it seems like I can't understand it, or doing something wrong.
Here's the code that I'm trying to implement:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Writing to the page</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<textarea id="area1" rows="15">something</textarea>
<button onclick="myFunction()">Click me</button>
<py-script id="demo">
print("Hello, world!")
</py-script>
<py-terminal></py-terminal>
<script>
function myFunction() {
var text1 = document.getElementById('area1').value;
document.getElementById("demo").innerHTML = text1;
}
</script>
</body>
</html>
It just prints the content of the textarea above the terminal, without executing the code and printing the output, inside the terminal, as I imagined.
I'm expecting to make this functinal, and I tried a few things, but unsuccessfully.
I also tried:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Writing to the page</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<textarea id="area1" rows="15">print("something")</textarea>
<script>
let text1 = document.getElementById('area1').value;
</script>
<py-script>
def print_to_page(x):
exec(x)
</py-script>
<button py-click="print_to_page(text1)" id="print">Run!</button>
</body>
</html>
But I'm not sure how to pass the variable from JS to PyScript.

This 'Answer' is meant to help in addressing:
"I tried different approaches, and would like to hear different oppinions [sic],"
You may want to check out this post:
https://twitter.com/jtpio/status/1523660682708668416 May 2022
"The #SymPy Online Shell is now powered by the #pyodide stack and JupyterLite💡
You can try the latest SymPy release directly in your browser, without installing anything, by visiting the following URL:
https://sympy.org/en/shell.html
Many thanks to Ivan Savov for leading this effort!"
Something like that may integrate well with your blog. You can hack around on it and hopefully put together what you need combined with that example and the documentation.
Related resources:
'Embedding the REPL on another website' section in the JupyterLite documentation
Embedding Jupyter Everywhere - Easily embed a console, a notebook, or a fully-fledged IDE on any web page.
Alternative approaches:
JupyterBook and MyST-NB seems to be moving along this route. For example see the Render option the left side there.
I'm not sure all the pieces are together but you can imagine with the JupyterLite/pyodide stuff it soon will be set for blogs.) Quarto may be heading that way, too.
See also Make Jupyter notebook executable in html format

Based on your description and the second example, it looks like you want to have a textarea where the user types in Python code, and run button that executes that entered code when clicked. If I've misunderstood your goal, you can disregard this answer.
The way to bring JavaScript objects/variables into Python is using Pyodide's import js syntax, which treats the JavaScript global namespace like a Python module. Here's a version very similar to your second example, which imports JavaScript's document object and uses that to extract the value of the textarea:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Writing to the page</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<textarea id="area1" rows="15">print("something")</textarea>
<py-script>
from js import document
def runTextInTag(id):
src = document.getElementById(id).value
exec(src)
</py-script>
<button py-click="runTextInTag('area1')" id="run">Run!</button>
</body>
To address your first example, which changes the innerHTML of the py-script tag itself: A <py-script> tag executes its contained code exactly once, when the custom element is attached to the DOM. This happens shortly after PyScript initializes and the custom HTML element <py-script> is defined, or when you add an additional <py-script> tag to the page.So, in your first example, setting the innerHTML/innerTEXT of a <py-script> tag does not cause that code to be executed again.
You could create a new <py-script> tag with the appropriate innerText and add it to the DOM, at which point its code would be executed, but I think the above method is cleaner for most purposes.

Related

Link two JavaScript files to work together on top of an HTML page

I have homework for my programming class which requires that I work with JS classes. On top of that, I have to work with HTML and the classes have to be defined on a separate .js file. I've done all the work, and it runs ok if the classes are defined on the same .js file, but it stops working as soon as I paste the code on a different file. I've tried importing the classes on the primary file, but I could make it work (I've tried different import codes because I've found different answers to this question on Google but no one worked, that's why I'm asking here). I believe it's probably because I'm doing something wrong at importing, but I just can't find the error.
Although your code works, keeping js files at the top of the HTML will delay the load time of the page. In a simple scenario like a homework, there's no need to worry, but in large projects it becomes crucial.
And by reading your code, it just starts when all page has already loaded, so no need to put it in the head.
Have you tried doing this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="first.js"></script>
<script src="second.js"></script>
<p>Hello World!</p>
</body>
</html>
First, I'll share some code. This is my HTML head:
<head>
<meta charset="utf-8">
<title>Obligatorio1</title>
<link rel="stylesheet" href="css/estilos.css">
<script src="js/funciones.js"></script>
<script src="js/clases.js"></script>
</head>
This is my relevant code on the first JS:
window.addEventListener('load',inicio)
function inicio(){
document.getElementById("botonAgregarPersonas").addEventListener("click",registroPersonas);
}
let personas=[];
function registroPersonas(){
let nombre=document.getElementById("nombrePersonas").value.trim();
let seccion=document.getElementById("seccionPersonas").value;
let mail=document.getElementById("emailPersonas").value.trim();
let esta=false;
for (i=0;i<personas.length&&!esta;i++){
if (nombre==personas[i].nombre) {
esta=true;
}
}
if (esta){
alert("Nombre ya ingresado");
}else {
let Per = new Persona (nombre, seccion, mail);
personas.push(Per);
let texto=Per.nombre+" - Sección: "+Per.seccion+" - "+Per.mail;
agregarElementoEnLista(texto);
agregarEnComboCompras(Per.nombre);
agregarCheckboxes(Per.nombre);
}
}
function agregarElementoEnLista (texto){
let nodoLi=document.createElement("LI");
let nodoTexto=document.createTextNode(texto);
nodoLi.appendChild(nodoTexto);
document.getElementById("lista").appendChild(nodoLi);
And this is the code of my second JS file (the one with the class):
class Persona{
constructor(nombre, seccion, mail){
this.nombre=nombre;
this.seccion=seccion;
this.mail=mail;
}
}
I'll start saying that, while I've found out the issue, I don't understand why does it happen.
Ok, as you can see on the last piece of code, the parameters have the same name as the class attributes. If I would try copying the code on the first JS file, it would work without any issue, but as soon as I work with that code on a separate JS file it would stop working. After touching every part of the code, I ended up changing the parameters name so it would be different than the class attributes, it looks like this now:
class Persona{
constructor(_nombre, _seccion, _mail){
this.nombre=_nombre;
this.seccion=_seccion;
this.mail=_mail;
}
}
And that code right there works totally fine, without changing anything on the rest of the files (neither the first JS file nor the HTML one).
If anyone understands more than me on why does this happens, feel free to edit this answer.
Thanks everyone for the help!

Inserting a javascript variable that is a mathjax command into a html page that outputs formatted maths

I have a variable in javascript that depends on an input from
<input type="text" id="inputfunction" value="">
<button onclick="example">Example</button>
<p id="input"></p>
In the js script I have used document.getElementById("input").innerHTML = inpt; to place this variable on the page.
The variable comes out similar to say '3x+8' however I want this to be formatted with mathjax. To facilitate this I currently have
<head>
<link rel='stylesheet' type='text/css' href='Stylesheet1.css'/>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
</head>
in my html document, however this doesn't output the variable formatted. I have tried using document.getElementById("input").innerHTML = \\(inpt\\); or placing $$ on either side of it however this just puts it on the page as \(inpt\) or $$inpt$$. Is there any way to have it so that mathjax formats the variable?
Okay so I eventually found it and it was a really easy fix. I just added
MathJax.Hub.Typeset();
at the end of the function and that makes MathJax look back over the page to format anything else. Apparently you shouldn't call this directly though because MathJax may be performing other actions so to counteract any issues this may cause you can write
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
which makes sure MathJax has finished all other processes before typesetting the page stop any synchronisation errors.

Accessing jQuery within a JavaScript namespace / module pattern [duplicate]

So classic problem, but having a horrible time on finding the actual cause. Typically when I see this error it's because the jQuery reference is after code requiring it, or back jQuery link, or jQuery conflict, etc... so far none of those appear to be the case. Unfortunately seeking out the solution to this problem has lead me to post after post of such cases. I'm sure my problem here is equally as simple, but over an hour of hunting, still no luck...
Edit: Additional information...
The solution file (which I've recreated multiple times trying to figure this out. Is a JavaScript Windows Store Blank App template and I'm doing this in Visual studio. The only references files is Windows Library for javascript 1.0, I have tried deleting this to test as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Template</title>
<style>
/* styles here */
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
<p>Canvas not supported.</p>
</canvas>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
function renderContent()
{
// we'll do our drawing here...
}
renderContent();
});
</script>
</body>
</html>
It's states that JQuery referred URL is not correct
Try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I tried everything listed above and nothing seems to work until I put this string
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
in the head section of the HTML file. So here's how it looks:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery Reference -->
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>some title</title>
</head>
<body>
...
And the js file is located at a level below in the folder 'scripts'.
Finally, the error is gone and what a relief!
In my case, the problem was that I was rendering my page over https but I was trying to request the JQuery file over http, which is blocked by many browsers for security reasons.
My fix was to change this...
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
...to this...
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
This causes the browser to download JQuery using the same protocol (http or https) as the page being rendered.
Some of my clients had this problem, because apparently they blocked loading Javascript from 3rd party sites. So now I always use the following code to include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery ||
document.write('<script type="text/javascript" src="/js/jquery-1.9.1.min.js">\x3C/script>')
</script>
This makes sure, that even if my client blocks loading the Javascript file from the CDN domain, the client still downloads the file from my own server, which is not blocked by the browser.
Anover variant, in my case - I was forced to use proxy. So - IE11--> InternetOptions --> Connections-->LANSettings-Proxy Server--> UseProxyServer - should be checked.
Also check awailability of jQUery script source, my worked variant in VS2012 - -just like in top example
I was getting this same error code:
(Error: 'generateText' is undefined)
...on the code
var bodyText=["The....now."]
I discovered on my text-editor(Notepad++), when typing many lines of text in the directly above the variable bodyText, if I didn't hit return carriage (enter==>WordWrap is off) just kept typing w/o return carriage and let the editor adjust text it worked?
Must be in the settings of Notepad++??

How to display variables from external JavaScript in HTML. Internet Explorer 7

I realize this is a horribly newbie question, but Ive been trying to fix it for days trying different methods so I just wanted to ask what would you do.
I am attempting to create a web program to use at work, and I have this setup:
Windows 7
IE 7 - Cannot Upgrade.
The "website" is not a webhost, basicly I have a folder on my desktop with html/css/js files and I use IE to run the scripts, no host.
I want to keep a set of vars, mostly strings, in an external JS file and pull the JS into different HTML pages. I want it to write on load of the document.. not on ready. It does not have to be user dynamtic.
Also, When I make the js file, does it have to have a header.. like HTML has doctypes?
I really appreciate your help as I am trying to learn and will cont on my own from here. My setup is much different than most, and im not sure which part was causing my problem so I finally broke down and posted.
When you write your JavaScript file it doesn't have to have any header or doctype. For example you can have a variables.js file that looks just like this:
var x = "abc";
var y = "def";
and have many HTML files that include variables.js like this:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<!-- page content -->
<script src="variables.js"></script>
<script>
alert(x);
</script>
</body>
</html>
and your variables should be available there. Any script that is included after the reference to your variables.js should have access to everything that was included before without the need to listen to any events.
If you need to listen to the events then I suggest to use jQuery or some other JavaScript framework. An example for jQuery would be:
$(window).load(function() {
alert(x);
});
A more advanced example of changing the DOM elements:
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>title</title>
</head>
<body>
<p>Select variable:</p>
<p>
Show x
Show y
</p>
<p>Value:</p>
<p id="value"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="variables.js"></script>
<script>
$('#show-x').click(function (e) {
e.preventDefault();
$('#value').html(x);
});
$('#show-y').click(function (e) {
e.preventDefault();
$('#value').html(y);
});
</script>
</body>
</html>
If it's not a global variable, you can't display/print/access or whatever you call it because it has a local scope, defined in a function.
You can probably only use a debugger simply to debug it

JavaScript runtime error: '$' is undefined

So classic problem, but having a horrible time on finding the actual cause. Typically when I see this error it's because the jQuery reference is after code requiring it, or back jQuery link, or jQuery conflict, etc... so far none of those appear to be the case. Unfortunately seeking out the solution to this problem has lead me to post after post of such cases. I'm sure my problem here is equally as simple, but over an hour of hunting, still no luck...
Edit: Additional information...
The solution file (which I've recreated multiple times trying to figure this out. Is a JavaScript Windows Store Blank App template and I'm doing this in Visual studio. The only references files is Windows Library for javascript 1.0, I have tried deleting this to test as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Template</title>
<style>
/* styles here */
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
<p>Canvas not supported.</p>
</canvas>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
function renderContent()
{
// we'll do our drawing here...
}
renderContent();
});
</script>
</body>
</html>
It's states that JQuery referred URL is not correct
Try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I tried everything listed above and nothing seems to work until I put this string
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
in the head section of the HTML file. So here's how it looks:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery Reference -->
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>some title</title>
</head>
<body>
...
And the js file is located at a level below in the folder 'scripts'.
Finally, the error is gone and what a relief!
In my case, the problem was that I was rendering my page over https but I was trying to request the JQuery file over http, which is blocked by many browsers for security reasons.
My fix was to change this...
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
...to this...
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
This causes the browser to download JQuery using the same protocol (http or https) as the page being rendered.
Some of my clients had this problem, because apparently they blocked loading Javascript from 3rd party sites. So now I always use the following code to include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery ||
document.write('<script type="text/javascript" src="/js/jquery-1.9.1.min.js">\x3C/script>')
</script>
This makes sure, that even if my client blocks loading the Javascript file from the CDN domain, the client still downloads the file from my own server, which is not blocked by the browser.
Anover variant, in my case - I was forced to use proxy. So - IE11--> InternetOptions --> Connections-->LANSettings-Proxy Server--> UseProxyServer - should be checked.
Also check awailability of jQUery script source, my worked variant in VS2012 - -just like in top example
I was getting this same error code:
(Error: 'generateText' is undefined)
...on the code
var bodyText=["The....now."]
I discovered on my text-editor(Notepad++), when typing many lines of text in the directly above the variable bodyText, if I didn't hit return carriage (enter==>WordWrap is off) just kept typing w/o return carriage and let the editor adjust text it worked?
Must be in the settings of Notepad++??

Categories

Resources