How to use Python function with JavaScript - javascript

I have a JavaScript file that is used for a google chrome extension, Also I have a Python file which has functions in it, only for the example let's imagine that in the python file we have a function like so
external.py
def name(x)
return "your" + x
So I want to call this function through JavaScript and get the return value inside of JavaScript, so if the Python file named external.py and the JS file named index.js for example, so the code will JS be something like that
index.js
data = "external.py".name("John") //(It doesn't have to be like that, just for the example)
I've tried using ajax but it does not work (I've tried to import jquery way too many times, but it doesn't seem to work) maybe because it's a google chrome extension.
Also, I've tried to use fetch but I have no idea how to write it exactly and if it's impossible with fetch.
I am new to JS though, so go easy with me.

Use this code.
Do ajax call in your js code.
It may help you.
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
Or you can ref to this link for js with python work https://pyscript.net/

Related

JSON get Javascript from API, but I want to get from my own work

So currently I have a code that get's random quotes from https://forismatic.com/en/api/ , using this code in my main.js file:
$.ajaxSetup({
cache: false,
"error": function() {
init()
}
});
function init () {
$.getJSON('https://cors-anywhere.herokuapp.com/https://api.forismatic.com/api/1.0/?method=getQuote&key=0&format=json&lang=en').then(function (data) {
$('blockquote').html(data.quoteText)
});
}
How can I change this so I can create my own sheet with quotes and display it on the same way?
You can't just add a flat file (or you can, but not with this method) with quotes on it, you need to create an API, which will require a server. You can use node.js for this if you are comfortable with javascript, but you can use any language really.
There are many simple guides online on how to do this, for Node.js they will generally use Express for the server, and some may suggest using a database such as MongoDB (I would suggest avoiding that for such a simple task at this point).

Extract variable from Javascript to Python function

I am using PyQt5 to create a small app. At some point I need to let the user select latitude and longitude from a map. After some research, the easiest way to implement a map search seems to be using google maps through some Javascript lines.
I found this code that does pretty much what I need:
https://gis.stackexchange.com/questions/33238/how-do-you-get-the-coordinates-from-a-click-or-drag-event-in-the-google-maps-api/33246#33246?newreg=eeb7c8c7ce344710838fba3d7b111d12
However, I need to use in my python function the coordinates selected by the user. How can I pass to python the latitude and longitude selected in the Javaascript code ("latLng")? I read a bunch of similar questions on many forums but I can't figure out how to solve my problem. I would expect to find a very simple solution.
My code is something like:
def latlong_function():
html='''
<html> <head> .... ....
'''
print(coordinates)
return html
I am not an expert when it comes to doing python backends for web apps, but I do have experience with PHP and perl in a web environment.
Unless python has a specific utility/library for doing this (and based on your research it sounds like it doesn't) your best bet is to have your JavaScript submit the data via an HTTP POST request using something like Ajax and JQuery.
Something like this might work:
// Function called when an HTML button with id of "Search_Button" is clicked
$('#Search_Button').click(function () {
// Get the values of your lat/long HTML inputs
var lat = $('#Latitude_Input').val();
var long = $('#Longitude_Input').val();
// Submit the AJAX request
$.ajax({
url: "path/to/your_script.py", // Path of the python script to do the processing
method: "POST", // Method to submit the HTTP request as, usually either POST or GET
data: { // These are the POST parameters passed to the backend script
latitude: lat,
longitude: long
},
success: function (returned_data) { // Function to run if successful, with the function parameter being the output of the url script
alert('Here is the output: ' + returned_data);
},
error: function () { // Function to run if unsuccessful
alert('An error occured');
}
});
});
This should let you take the data from the HTML page and let your python script process it.
Check out this answer for handling POST/GET requests in python.

Update a variable dynamically in flask

I m working with flask and need to make a python variable appear on a HTML page & update it in real time without the need to refresh . i have searched but couldn't do it. To find a solution the simple way i have created in the python script a time variable that should be updated in the page dynamically.Here is my code:
<script>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
(function(){
$.getJSON(
$SCRIPT_ROOT+"/get_data",
function(data) {
$("#testt").text(data.time);
}
setInterval(arguments.callee, 1000);
);
});
</script>
<span id="testt">?</span>
import datetime
from flask.app import Flask
from flask.json import jsonify
app=Flask(__name__)
#app.route('/get_data', methods=['GET'])
def get_data():
return jsonify(time=str(datetime.datetime.now().time()))
if __name__=="__main__":
app.run(debug = True, host='0.0.0.0')
EDIT: In my solution the time only updates when i refresh the page . want it to update in real time.
You don't specify what's your problem exactly ("doesn't work" doesn't really help) so this can be a wild-guess answer at best.
First point, you define an anonymous function but never call it, so the chances it ever gets executed are strictly equal to zero. If you want that function to be executed when your dom's ready (which is the sane thing to do since it references an element of the dom that is defined after the function, you can use $(document).ready(yourfunc), ie:
$(document).ready(function(){
$.getJSON(
$SCRIPT_ROOT+"/get_data",
function(data) {
$("#testt").text(data.time);
}
setInterval(arguments.callee, 1000);
);
});
Also you certainly don't want to call window.setInterval() from the function that itself (which would then be called again an again each time the function is called), so it should rather be something like:
$(document).ready(function(){
function _update_time() {
$.getJSON(
$SCRIPT_ROOT+"/get_data",
function(data) {
$("#testt").text(data.time);
});
}
// do a first call at load time
_update_time();
// then repeat it every second
window.setInterval(_update_time, 1000);
);
});
Also, I'm not a Jinja2 expert (since it's Flask and from the look of it I assume Jinja2 templating), but this:
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
seems uncorrect to me.
First, you want $SCRIPT_ROOT to be a string, so you have to quote it:
$SCRIPT_ROOT = "{{ request.script_root|tojson|safe }}";
Then I don't see the point of the tojson and safe filters here - safe tells the template engine to not html-escape your variable but an url seldom contains html markup, and jsonifying a simple string doesn't make sense to me.
Once again it's wild-guess at best and possibly completely wrong. If you want better answers you will have to do your homework and post some more informations, including:
the rendered html (well the relevant part that is)
any error message in your browser's inspector window / debug toolbar / however it's called in your browser.
You can update your page dinamically using a websocket.
There is a project named Socket.Io which is implemented by Flask to work with websockets.
You can read the documentation here : https://flask-socketio.readthedocs.io/en/latest/ and watch a quick example to understand the concepts here : https://www.youtube.com/watch?v=RdSrkkrj3l4

Issue executing Perl CGI from JavaScript

How do I get my Perl script to execute from JavaScript called from an HTML form's 'action' attribute?
I am using scripts built by other people mostly, and the basic gist of it is that I need to call the CGI script from the JS function.
I have to do it this way because it was the best I could come up with based on whether or not the device is mobile.
I need to pass some checkboxes to the Perl script and return some files based on the checkbox states. I know the Perl script works perfectly without having to execute the JavaScript, but I don't know how to check if a device is mobile or not in Perl, and I do in JS.
All I need is to execute the CGI script, passing it the same information as if it was being called directly from the form, but it does nothing.
Here is my JavaScript:
function downloadFiles(){
var isMobile = function(){
try {document.createEvent("TouchEvent"); return true;}
catch(e) {return false;}
}
&& (/Mobi/i.test(navigator.userAgent));
if(!isMobile){
$.ajax({
type:"Post",
url:"https://www.mywebsite.com/cgi-bin/myPerlScript.cgi",
success:function(msg){$("#myHtmlForm").html(msg.d);}
});
}
}
I don't rightly know what 'msg' or its property 'd' is, and I don't even know if my form should be the element where it is. So what I am missing here?
It turns out that I wasn't building the ajax statement completely or correctly. I didn't add any data that I needed to pass into the CGI script.
Here's the ajax statement I ended up with:
$.ajax({
type:"POST",
url:"/cgi-bin/myPerlScript.cgi",
data:$("#myHtmlForm").serialize(),
error:function badCall(){location.href="https://www.mywebsite.com/error.html";}
});
Thank you #ikegami, #mkHun, #simbabque, and #DaveCross!

Can user's custom JavaScript on MediaWiki call a Lua module?

On MediaWiki wikis each user has a user JavaScript page they can put code in, much like GreaseMonkey but without extensions. Such as at User:YourUsername/vector.js
MediaWiki has also had an embedded Lua, called Scribunto, for a little while now.
I know Lua modules can be called from MediaWiki templates, and I suppose that's their main use. But Googling and hunting around the MediWiki docs I can't find whether there's a way to call a Lua module from your user JavaScript.
(I need to map names of languages to language codes in my JS and there's a Lua module to do just that without me duplicating the code (mainly data) in a second language.)
You can't do this directly, because JS runs on the client and Lua on the server. What you can do is to use the MediaWiki API from JS to invoke the module. Specifically using the expandtemplates API module.
For example, if you wanted to call the function h2d from Module:Hex with the parameter FF ({{#invoke:hex|h2d|FF}} in wikitext) and alert the result, then the JS would look like this:
var api = new mw.Api();
api.get( {
action: 'expandtemplates',
text: '{{#invoke:hex|h2d|FF}}'
} ).done ( function ( data ) {
alert(data.expandtemplates['*']);
} );
And for the OP's specific case, running on the English Wiktionary:
var langName = 'Esperanto';
(new mw.Api()).get({
action: 'expandtemplates',
format: 'json',
prop: 'wikitext',
text: '{{#invoke:languages/templates|getByCanonicalName|' + langName + '|getCode}}'
}).done(function(data) {
alert('Language name: ' + langName + '\nLanguage code: ' + data.expandtemplates.wikitext);
});
(prop: 'wikitext' avoids a warning from the API and lets you access the result as data.expandtemplates.wikitext rather than the slightly mystifying data.expandtemplates['*']. Otherwise there's no difference.)

Categories

Resources