Here is a function in javascript which is currently being used to update a database. Currently when it is run, the entire python script is outputted to the javascript function intead of just the print statement. Is it possible, without importing any extra modules, for data to be sent between these two sections of code? if so, how would I do it?
Javascript:
function sendmsg(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText)
document.getElementById("name").innerHTML = '';
}
};
xhttp.open("GET", URL+'/SendMsg.py', true);
xhttp.send();
}
Python:
import cgi
import cgitb; cgitb.enable()
import sqlite3
mydb = 'messenger.db'
conn = sqlite3.connect(mydb)
cursor = conn.cursor()
print('alex')
"""
form = cgi.FieldStorage()
Sender = form.getvalue('UserName')
Reciever = form.getvalue('Class')
message = form.getvalue('Message')
val = {"Sender":Sender, "Reciever":Reciever, "message":message}
cursor.execute('''INSERT INTO Message (Message, SenderID, ClassID) VALUES (:message, :Sender, :Reciever)''',val)
conn.commit()
cursor.close()
"""
Many thanks in advance
Ive fixed this problem, There was a error in the config file of apache which didnt allow python cgi to run how it is created to run. For future, make sure that the required lines of code in the config files are uncommented.
I would suggest to take a look at Flask or Django. You can implement a RESTful API using Django or Flask, read the HTTP request there, extract parameter and send back appropriate response.
Right now you are requesting the server to send xhttp.open("GET", URL+'/SendMsg.py', true); SendMsg.py and it's sending that.
Related
I'm working on some changes to a page that needs to retrieve information from some files under /proc so the page can display version information to the user. Currently, the page is generated entirely by the Python script, which allows me to just read the file and put everything in the page at creation time.
However, this led to the issue that the version numbers wouldn't update when a new version of the software was uploaded. I don't want to regenerate the page every time a new package is installed, so I made the main page static and want to instead just query the information from a Python script and return it to the page to populate the page when loaded.
The Python scripts are set up as CGI and have sudo access, so there's no issue with them retrieving those files. However, if I wanted to use something like AJAX to call the Python script, is there any way I could return the data without using a REST framework such as Flask or Django? The application needs to be lightweight and preferably not rely on a new framework.
Is there a way I can do this with vanilla JavaScript and Python?
Ok, so the solution was fairly simple, I just made a few syntactical errors that led to it not working the first few times I tried it.
So the request looked like this:
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if((this.readyState == 4) && (this.status == 200)) {
var response = JSON.parse(this.responseText);
// Do stuff with the JSON here...
}
};
xhr.open("GET", scriptURL, true);
xhr.send();
}
From there, the Python script simply needed to do something like this to return JSON data containing my version numbers:
import sys, cgi, json
result = {}
result['success'] = True
result['message'] = "The command completed successfully"
d = {}
... write version information to the 'd' map ...
result['data'] = d
sys.stdout.write("Content-Type: text/plain\n\n")
sys.stdout.write(json.dumps(result))
sys.stdout.write("\n")
sys.stdout.close()
The most persistent problem that took me forever to find was I forgot a closing quotation in my script tag, which caused the whole page to not load.
I am in need of a little help with a small bit of my code that is essential to my application. I am making a small clicker game, and I want users to be able to save and load data via PHP to my server. I do not want to use Local Storage to make it harder for anyone to edit their economy and "cheat". When the user clicks on a save button I have, it fires my vue method which initializes the saving. I have had no problem getting the data into a JSON format, however I cannot get PHP to read this data via POST. I have checked for network headers, and it shows that stuff is being sent, it seems that PHP just isn't catching it. I'll include the code for the JS part and PHP part below. The PHP is only set to echo if the array_key_exists right now, as after getting this sorted out I will easily be able to handle the rest. Any help would be greatly appreciated!
I have tried to follow this, which has not worked so far Send JSON data from Javascript to PHP?
JS
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
console.log(saveData);
}
PHP
<?php
if (array_key_exists("saveData", $_POST)) {
echo "<p>SALO Ready!</p>";
}
?>
Decode the JSON string at the PHP end before accessing values, like this:
<?php
if(isset($_POST['saveData'])){
$result = json_decode($_POST['saveData'], true);
// use $result['saveMoney'] and $result['saveCrystals'] accordingly
}
?>
Update# 1:
As OP commented below, I expect that it will print "SALO Ready" but it is instead doing nothing
That's because you are not using responseText property of XMLHttpRequest object to see the text received from the server. Use below snippet to see the response text.
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText
OK, so I have many quizzes which previously worked fine on my http:// website, using AJAX javascript calls to a php mailer program to send data about the quiz and mail it to the recipient.
I have upgraded the site to https:// and now none of the scripts work. The bones of the javascript are contained in the following function:
function postIt() {
var http = new XMLHttpRequest();
var url = "../mail/summary.php";
var params = "realname="+myName+"&rightAnswers="+correct+"&percentageScore="+percentage+"&wrongArray="+wstore+"&asked="+numq+"&mins="+minutes+"&secs="+seconds+"&deliver="+destination+"&testName="+test;
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() { //Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(null);
}
The php mailer receives the variables and mails them. Again the bones of the php are below:
$data1=$_GET["realname"];
$data2=$_GET["rightAnswers"];
$data3=$_GET["asked"];
$data4=$_GET["mins"];
$data5=$_GET["secs"];
$data6=$_GET["percentageScore"];
$data7=$_GET["deliver"];
$data8=$_GET["testName"];
$myWrongArray = explode(',', $_GET["wrongArray"]);
$sendTo = "results#ibchem.com".", ".$data7;
$subject = $data8." summary results for ".$data1;
The code is fine for http:// websites (I have tested it again on http://mypchem.com/test) but fails on https://ibchem.com/test.
My level of understanding is pushed to the limit as I can code (average) in javascript, html, css, php etc. but have no idea how to solve this problem.
Any help please?
Charco
I'm making a Design Studio custom component in Eclipse. I created a property 'backgroundColor' in my contribution.xml file. I can call this xml file inside my javascript and adjust it locally, but is there a way I can upload these changes to the server xml file again? Cause at the moment my alerts return all the new data but on the server side nothing happens.
Code that i have:
Contribution.xml:
<property
id="backgroundColor"
title="BackgroundColor"
type="Color"
group="Display"
visible="true"
bindable="true"/>
component.js:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "serverpath/contribution.xml", true);
xhttp.send();
function myFunction(xml) {
xml.responseXML.getElementsByTagName('property')[0].setAttribute("visible",false);
//this returns BackgroundColor so the call does work
alert(xml.responseXML.getElementsByTagName('property')[0].getAttribute("title"));
}
You will need to make some server side coding to do that. You could achieve that by making simple rest api. But otherwise without any server side coding you cant do that. You are now getting data with GET request to server which means you cant do any modifications, you simply get any server response data.
I'm trying to save a few lines of text in a textarea with ajax targeting a classic asp file.
I'm not sure how to use ajax when when it comes to sending data with POST method and NOT using jQuery, didn't find any questions concerning this here either, no duplicate intended.
Ajax function:
function saveDoc() {//disabled
var xhttp = new XMLHttpRequest();
var note = document.getElementById("note");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("0").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "saveNote.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(note);
ASP Classic:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\1.txt",8,true)
dim note
note = RequestForm("note")
f.Write(note)
f.Close
Response.Write("Works.");
set f=nothing
set fs=nothing
I'm aware there might be a lot wrong with the .asp since i couldn't find any specific info about how to handle ajax requests with Classic ASP correctly.
Any suggestions on how to make this work without jQuery are welcome.
I cannot test your code as I don't have a backend running on my machine right now. But I can already tell you a few things:
you are calling xhttp.send(note); but your note is a DOM element. It should be a string with a querystring format.
in your server side code you call RequestForm is it a custom function you have previously defined ? The usual syntax is Request.Form
Hope it can help