Pass an argument from javascript to a python script - javascript

I have a python script from which I pass an argument to execute a query in an Oracle Database
prov.py
#!/usr/local/bin/python2.7
import sys
import argparse
import cx_Oracle
import json
import cgi
import cgitb
cgitb.enable()
lst_proveedores=[{}]
conn_str = 'user/pass#DATABASE'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
qstr = qstr = """ select id_proveedor, nombre, tipo from mpc_proveedores where tipo = '%s' """ %sys.argv[1]
c.execute(qstr)
for row in c:
record1 = {"id":row[0], "nombre":row[1],"tipo":row[2],"tipo":row[2]}
lst_proveedores.append(record1)
json_string = json.dumps(lst_proveedores)
print json_string
conn.close()
I need to show the data in an HTML page.
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "prov.py", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-Type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML +=
"<tr><td>"+data[obj].id+"</td><td>"+data[obj].nombre+"</td><td>" +data[obj].tipo+"</td></tr>";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div class="container">
<div class+"row">
<table id="results" class="table table-bordered table-striped table-hover">
<tr>
<td>Id Proveedor</td>
<td>Nombre</td>
<td>Tipo</td>
</tr>
<script type="text/javascript">ajax_get_json();</script>
</table>
</div>
</div>
</body>
</html>
How can I execute the script from a button, and how can I pass a value from an input text to javascript?
Also, I know my javascript is not well designed. Any advice?

To run Python code from Apache you need to use a proper interface for it. There are many posibilities but CGI or mod_wsgi are popular alternatives. The Python docs has lots of useful info about how to set it up.

I think what you really want is a web framework.
That would provide a structured approach to exactly the type of stuff you're trying to do.
django is great and very popular. Pyramid and Flask are also very popular.
I have a good amount of experience with Flask and highly recommend it.

Related

how to fetch content of a webpage post-translation (after window.load event??)

I'm currently coding a Flask application with a simplified version of my code below.
#app.py
from flask import Flask, render_template, request
# Configure application"'
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config\["TEMPLATES_AUTO_RELOAD"\] = True
#app.route("/")
def index():
return render_template("gettranslation.html")
#app.route("/translate")
def translate():
word = request.args.get("word")
lang = request.args.get("lang")
return render_template("translate.html", lang = lang, word=word)
The default webpage should log a translation of the given words, but instead it just logs the word before translation, though when visited the webpage being fetched takes a second to load and then shows the correct translation. How do I fetch this correct translation?
Here is simplified code from my two files:
<!--translate.html-->
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<div id="google_translate_element"></div>
<p id="to-translate">{{word}}</p>
<script>
var lang = "{{ lang }}";
var lang = lang[0] + lang[1];
console.log(lang);
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{
pageLanguage: lang
},
"google_translate_element"
);
}
window.href = window.href + "/#googtrans(" + lang + "|en)";
</script>
<!--gettranslation.html-->
<script>
async function translate(sourcelang, destlang, word){
var url = '/translate?word=' + word + "&lang=" + sourcelang + "/#googtrans(" + sourcelang + "|" + destlang + ")";
console.log(url);
let response = await fetch(url, {redirect: 'follow'});
let text = await response.text();
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(text, 'text/html');
var translation = htmlDoc.getElementsByTagName('p')[0].innerHTML;
console.log(translation);
}
translate("fr", "en", "bonjour");
</script>
I thought using await or redirect: follow would work but neither did. I also got the idea to use #googletrans("source|dest") from this question: Trigger Google Web Translate Element if that's helpful.
Someone there saidthe Google translate select box is created after the window.load event triggers, so that is could be what is messing up my fetch request but if so I have no idea how to fix that.
Thanks in advance!
The html template is rendered at server side, this might be causing the problem with your script.
Why don't you translate the words in flask and then send them to the template? There are libraries for that such as Flask-Googletrans Flask-Googletrans.
You can translate in the view function:
from flask_googletrans import translator
ts = translator(app)
in the jinja template
<h1>{{ translate(text='your text', src='en', dest=['fr']) }}</h1>
I hope this helps

Retrieving data from database using js,php,ajax

I want to retrieve data from a database which is locally installed.
But the website is written and controlled with js, so I have to send an ajax request to a php-file, which then connects to the database, sends the query and later the result back to js.
I have a couple of files, because i followed this tutorial from 2012: https://www.youtube.com/watch?v=Yb3c-HljFro
The structure:
|-ajax (Folder)
| |-pkmn.php
|-db (Folder)
| |-connect.php
|-js (Folder)
| |-global.js
|-index.php
The files:
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meta>
</head>
<body>
Type: <input type="text" id="type"></input>
Tier: <input type="text" id="tier"></input>
<input type="submit" id="submit" value="Suchen"></input>
<div id="pkmn-data"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
global.js:
$("#submit").click(function () {
var type = $("type").val();
$.ajax("ajax/pkmn.php", {type: type}, function(data) {
alert(data);
});
});
connect.php
<?php
mysql_connect('localhost','root', '123456');
mysql_select_db('database');
pkmn.php:
<?php
echo 'Hello';
The user should enter something into the text-inputs, then click submit and the global.js-file sends that text to the file pkmn.php via an ajax request.
But when I click the submit-button, I receive an error:
XML-Verarbeitungsfehler: Ungeschlossenes Token
Adresse: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/pkmn.php
Zeile Nr. 1, Spalte 1: pkmn.php:1:1
XML-Verarbeitungsfehler: Ungeschlossenes Token
Adresse: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/index.php
Zeile Nr. 1, Spalte 1: index.php:1:1
Which says something like:
XML-Parseerror: unclosed token
at: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/pkmn.php
Row 1, Column 1: pkmn.php
XML-Parseerror: unclosed token
at: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/index.php
Row 1, Column 1: index.php
I have absolutely no idea, what could cause this error.
Furthermore: When I close the php-tag in pkmn.php the console says BOTH errors moved to Row 3 Column 3 and when I close the php-tag one line later (by adding another newline) the error again moves in both files one down. I can also add spaces in front of the closing tag, moving the errors horizontally.
I have never seen something like this before, so please help me to fix that.
Best regards,
PanCave
EDIT:
changing the global.js according to this tutorial (https://www.w3schools.com/php/php_ajax_database.asp) now produces an "no root element found" error :/
$("#submit").click(function () {
var type = $("#type").val();
var tier = $("#tier").val();
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("pkmn-data").innerHTML = this.responseText;
}
};
xmlhttp.open("Get", "pkmn.php?type="+type+"&tier="+tier);
xmlhttp.send();
});

obtain "server side" variable for use in html/javascript function

I'm trying to develop a language web application. It will scrape data from various websites and ask the participant numerous questions etc. I have created the file that scrapes the web page but I'm having difficulty getting the scraped variables from the node.js file. below are some extracts from the node js file:
var pword = function() {
var request = require("request");
var cheerio = require("cheerio");
var aa = Math.floor(Math.random() * 588);
var words = ['abash', 'aberrant', .....]
var A = words[aa];
var urlcollinsdictionary = "http://www.collinsdictionary.com/dictionary/english/";
var Newurldictionary = urlcollinsdictionary + A;
request({
uri: Newurldictionary,
}, function(error, response, body) {
var $ = cheerio.load(body);
$('div.homograph-entry').each(function() {
var link = $(this);
var text1 = link.text();
console.log(A);
console.log(text1);
});
});
}
My node js code works fine. my problem arises when I try to use its "text1" variable or others of its kind in my HTML/javascript coding. I've tried "getelementbyid", "variable exports/imports", even the "%%" method. but still no luck. as you've probably get guess I'm new to programming. please please please help me by making alterations/additions to the HTML code beneath to enable access to the text1 variable and others like it
<html>
<head>
language game
<title>language game</title>
<br>
<input type = "button" onclick = "word()" value = "Professional Vocab">
</head>
<body>
<script>
function word(){
alert(text1);
}
</script>
</body>
</html>
Thanks in advance...
You can add similar code in your node js file to respond to api calls
var express = require("express");
var app = express();
app.get("sendVar", function(request, response){
response.send(text1);
}
you will need to do npm install express in your command line
In your front-end side you can use jquery and make an AJAX call inside function word()
function word(){
$.get("url/sendVar", function(data){
alert(data);
});
}

Translate simple Perl script into Python that sends a response to client?

I'm really new to Python and my goal is to have the Python script print something to the client, and then display this on my webpage.
Fortunately, I stumbled upon a small code snippet that does exactly what I want to achieve with Python - unfortunately it is written in Perl.
I was wondering if anyone out there could show me how to write the Perl script in Python?
Here is the link that has all the code: http://www.degraeve.com/reference/simple-ajax-example.php
Here is the Perl script:
#!/usr/bin/perl -w
use CGI;
$query = new CGI;
$secretword = $query->param('w');
$remotehost = $query->remote_host();
print $query->header;
print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>.</p>";
How could I say the same thing in Python?
Here is the HTML page too:
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/ajaxTest.pl")'></p>
<div id="result"></div>
</form>
</body>
</html>
Something like this should work.
#!/usr/bin/env python
import cgi
import os
import cgitb; cgitb.enable() # for troubleshooting
form = cgi.FieldStorage()
secretword = form.getfirst("w", "")
remotehost = cgi.escape(os.environ["REMOTE_HOST"] if "REMOTE_HOST" in os.environ else os.environ["REMOTE_ADDR"])
print "Content-Type: text/html"
print # blank line, end of headers
print "<p>The secret word is <b>" + secretword + "</b> and your IP is <b>" + remotehost + "</b>.</p>"
Edit 1: How to list all environment variables.
for k in os.environ.keys():
print "<b>%20s</b>: %s<\br>" % (k, os.environ[k])

Invoking WebMethods with XmlHttpRequest and Pure JavaScript

I have what should be a relatively simple task that's frankly got me stumped. I've researched it until my brain is fried, and now I'm punting, and asking you guys for help.
Here's the scenario:
I have an ASPX page (Q2.aspx) that is decorated with the WebService,
WebServiceBinding, and ScriptService attributes.
That page contains a method, GetAllContacts, that is decorated with the WebMethod
attribute and returns a string containing JSON data. (For what it's worth, the page
itself contains no other controls or functionality.)
I have an HTML page that contains JavaScript which uses the XmlHttpRequest
object to invoke the GetAllContacts WebMethod on the ASPX page and transform
the JSON data into an HTML table.
I have verified that my Web.Config file contains the appropriate protocol handlers
for HttpGet and HttpPut in the WebServices section under System.Web.webServices.
I have verified that my Web.Config file contains the ScriptModule entry under the
System.webServer.modules section, and that it matches the appropriate documentation.
However, when I view the HTML page in a browser, the following occur:
The web request goes through, but the results are for the unprocessed HTML from the ASPX page.
The GetAllContacts method is never invoked, as evidenced by setting a breakpoint in its code.
The code to invoke the Web service, however, is invoked, and the JavaScript callback
function that is invoked upon request completion is properly invoked.
It appears that the JavaScript code is largely set up correctly, but for some reason that is completely escaping me at this point, the HTML page will simply not execute the WebMethod on the ASPX page, and simply returns the page as though it were a plain HTML GET request. Clearly, an HTML document can't be evaluated by JavaScript's eval function, which brings me to my problem. (Also note that the JSON data appears nowhere in the HTML that's returned.)
I am, frankly, baffled. I've looked at dozens of Microsoft articles, StackOverflow posts, CodeProject articles, and who knows what else. My code looks like it's okay. But I know better. I'm missing something simple, stupid, and obvious. I just need someone to point it out to me.
Below you'll find the ASPX page code and the HTML code, in the hope that they'll shed some light.
ASPX Code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
<body>
<form runat="server" id="frmMain"/>
</body>
</html>
-- Codebehind
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace Satuit
{
[WebService(Namespace="http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public partial class Q2 : Page
{
[WebMethod]
public static string GetAllContacts()
{
return LoadJsonData();
}
private static string LoadJsonData()
{
using (var stringWriter = new StringWriter())
{
string xmlUri = HttpContext.Current.Server.MapPath("\\XmlData\\Contacts.xml");
string xslUri = HttpContext.Current.Server.MapPath("\\XmlData\\Q2.xsl");
using (var xmlTextReader = new XmlTextReader(xmlUri))
{
var xpathDocument = new XPathDocument(xmlTextReader);
var xslTransform = new XslCompiledTransform();
xslTransform.Load(xslUri);
xslTransform.Transform(xpathDocument, null, stringWriter);
return stringWriter.ToString();
}
}
}
}
}
HTML Code
var objectData; // Receives the objectified results of the JSON request.
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("GET", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200)
{
var jsonResultBuffer = xmlhttp.responseText;
objectData = eval(jsonResultBuffer);
DisplayTable();
}
}
};
xmlhttp.send(null);
function DisplayTable()
{
var sHtml = "";
sHtml = "<table><tr><th>ID</th><th>First</th><th>Last</th><th>Address</th></tr>";
for(i = 0; i < objectData.length; i++)
{
sHtml += "<tr>";
sHtml += "<td>" + objectData.ID;
sHtml += "<td>" + objectData.firstName + "</td>";
sHtml += "<td>" + objectData.lastName + "</td>";
sHtml += "<td>" + objectData.address + "</td>";
sHtml += "</tr>"
}
sHtml += "</table>"
document.getElementById("divTable").innerHTML = sHtml;
}
</script>
Dev Environment Details
Vista Ultimate SP 2
Visual Studio 2008
.NET Framework 3.5
Solution has not yet been deployed, so it's running in the "local Web server"
provided by Visual Studio. (Makes me wonder if I shouldn't just deploy IIS
under Vista.)
Note that the ASPX page containing the WebMethod and the HTML page reside within
the same solution.
I think we need to call web method with POST request
try changing this part of code
xmlhttp.open("POST", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var jsonResultBuffer = JSON.parse(xmlhttp.responseText);
objectData = jsonResultBuffer.d;
DisplayTable();
}
};
Response is returned in JSON format with "d" as the key in xmlhttp.responseText
Pls try the following using jquery to see the web service is accessible or not.
$.ajax({
type: "POST",
url: "Q2.aspx/GetAllContacts",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("success");
},
error: function(response, aa) {
alert("fail");
}
});
Thurein

Categories

Resources