So I'm trying to make a problem for a ctf, and for a problem, I need to send data from a python script to the javascript. Can anyone tell me how?
Thanks!
My html code is:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 class="text">text</h1>
<script>
$.get("http://[website]/cgi-bin/challenge.py",
function(data) {
$(".text").html(data);
});
</script>
</body>
</html>
I replaced the website name with [website]
The python code is like this:
#!/usr/bin/python
import json
print "Content-type: text/html\n\n"
text = "It works!"
json.dumps(text)
Edit:
I expected the python file to return "It works!", however after going into the network tab to see the result, it returned nothing. The text in the h1 also disappeared.
This is an image from the network tab:
https://i.stack.imgur.com/8JSMO.png
You missing print() and content-type application/json because json.dumps() will not print output or set header to JSON.
#!/usr/bin/python
import json
text = json.dumps("It works!")
print "Content-Type: application/json\n"
print(text)
Related
I'm trying to create a code editor in react. I'm alredy done with outputting console.log value to my custom console component. I did this by overriding the console.log but now i'm stuck how to output for example python print: "print('hello')".
Source from which i overridden the console.log
Do you want to create an editor in the browser, that accepts python code and outputs its results when run?
For Python, you could use Brython.
<head>
<script src="https://cdn.jsdelivr.net/npm/brython#3/brython_stdlib.js"></script>
<script src="https://cdn.jsdelivr.net/npm/brython#3/brython.min.js"></script>
<script type="text/python">
from browser import window
def execute(code):
return eval(code)
window.python = execute
</script>
<script>
function runPython() {
const code = document.getElementById('input').value
if (!window.python) {
// Python not loaded yet
return setTimeout(runPython, 1000);
}
const output = window.python(code);
document.querySelector('.output').innerText = output
}
</script>
</head>
<body onload="brython()">
<textarea id="input" rows="4">
1 + 2
</textarea>
<button onclick="runPython()">Run</button>
<pre class="output"></pre>
</body>
Creating a code editor in the browser is a huge challenge. Best of luck!
I have an java application running, with a REST #POST endpoint, which takes an SQL query, and returns the result in a csv format.
The endpoint works, I can get the correct results via Curl and Postman.
Now, I am trying to call this endpoint via javascript, and to update a HTML value with the response. But have no experience with js.
This is the code I am using:
<!DOCTYPE html>
<html>
<body>
<h1>Making A POST</h1>
<p id="demo">Change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function loadDoc() {
$.post("http://localhost:4567/query/sql/csv",
"SELECT * FROM testTable",
function(data,status){
document.getElementById("demo").innerHTML = $result;
});
}
</script>
</body>
</html>
It is successfully making the POST request, can see from the application console. But it is not changing the HTML element with the response:
<p id="demo">Change this text.</p>
As I see, you're using a var that is undefined: $result
I think you wanted to use data instead.
Like this: document.getElementById("demo").innerHTML = data;
Code works.
The issue was Chrome and Internet Explorer blocking the script.
I'm trying to get images to display in real-time only on my machine. Think a really basic version of Google Images. The user types in "red hammer" and I show them a picture of red hammer
The problem is the refresh rate. I update the image file to be shown, and when I look it up directly as http://127.0.0.1:6007/static/tree.jpg, that will immediately give me the most recent jpg. And then, strangely enough after I look up something like http://127.0.0.1:6007/static/tree.jpg, the image changes on the initial http://127.0.0.1:6007 !
My setup:
In the static/ directory, tree.jpg:
templates/
show.html
In templates/, show.html:
<!DOCTYPE html>
<html>
<body>
<h1>Text-to-Image Synthesis</h1>
<form method="POST" action="/generator">
<p>Input to Generator: <input type="text" name="input_text"><input type="submit" value="Generate Image"></p>
</form>
<img src="{{url_for('static', filename='tree.jpg')}}" />
</body>
</html>
index.html
and index.html:
<!DOCTYPE html>
<html>
<body>
<h1>Text-to-Image Synthesis</h1>
<form method="POST" action="/generator">
<!-- button -->
<p>Input to Generator: <input type="text" name="input_text"><input type="submit" value="Generate Image"></p>
</form>
</body>
</html>
These two are the same except show.html shows the image on the src=... line.
server.py
#!/usr/bin/env python2.7
import os
from flask import Flask, request, render_template, g, redirect, Response, send_from_directory
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__, template_folder=tmpl_dir)
#app.route('/')
def index():
return render_template("index.html")
#app.route('/generator', methods=['POST'])
def generator():
# save typed-in text
text = request.form['input_text']
filename = "/home/ubuntu/icml2016/scripts/cub_queries.txt"
with open(filename, "a+") as f:
f.write(text + "\n")
"""
print('start')
subprocess.call('./scripts/demo_cub.sh', shell=True) # change the image in the background
print('end')
"""
return render_template("show.html")
if __name__ == "__main__":
HOST='0.0.0.0'
PORT=6007
app.run(host=HOST, port=PORT)
So now if I've properly given you everything, you should be able to call python3 server.py and see this:
and if you type in "hi" to the box it'll show this:
but when I change tree.jpg to some other image in the background and type in something else, I don't get the instant image update I'm looking for. In other words, that tree won't become the most recent tree :( We want to see Maury's beautiful face on my basic webpage
Your problem relates to http caching - read about the http Expires header. Flask defaults to setting an Expires header of 12 hours. This instructs your web browser that there is no need to ask for tree.jpg again for 12 hours. When your browser needs tree.jpg again it will simply load it from cache, it will not even make a request to your server. Manually entering this tree.jpg URL in your browser overrides this, in doing so you ask your browser to request it again.
You don't appear to have provided the relevant code -- the send_from_directory call serving your static file is where you need to make change.
send_from_directory(directory, filename, cache_timeout=0)
Relevant documentation:
http://flask.pocoo.org/docs/0.12/api/#flask.send_from_directory
http://flask.pocoo.org/docs/0.12/api/#flask.send_file
and send_file_max_age on the same page (the default Expiry)
I am having difficulty with a specific JQuery $.post call to a PHP-based processor. I created a test page with the code below located here: http://goo.gl/Bg7H2u
Note this is located on a subdomain, but we are not doing cross-domain posting. Everything should be included on the subdomain.
There do not seem to be any JS errors as reported in the error console.
The processor /get-data.html is the general purpose PHP processor, and, if you load the processor page with the right value, it returns a dataset from the MySQL database in JSON format. We have this working on the main domain without issue, and other $.post calls seem to work OK from this subdomain (not to this /get-data.html processor, but other processors that process form content).
See the actual processor output here: http://goo.gl/yOzrm2
I must be missing something obvious, but I am coming up empty. Thoughts?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320px, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var prices;
$(document).ready(function(){
$.post( "/get-data.html", { table: 'prices' },
function( data ) {
prices = data;
alert(prices);
}, 'json');
});
</script>
</head>
<body>
<div style="overflow-x: hidden;" id="divMain">
</div>
</body>
</html>
Thanks for any advice you can provide.
If you do View Source on the processor output, you'll see that your script is returning:
<p>{"Basic Plan":["349"],"Basic":["349"],"Premium Plan":["549"],"Premium":["549"],"Standard Plan":["429"],"Standard":["429"],"Bonus Plan":["175"],"Additional Central AC System":["99"],"Additional central heating system":["99"],"Central Vacuum":["99"],"Whole home humidifier":["49"],"Pool (in-ground)":["179"],"Spa (in-ground)":["179"],"Septic System":["99"],"Sump Pump":["99"],"Well pump":["99"],"Whole home water softener":["99"],"Lawn sprinkler system (in-ground)":["99"],"Wine refrigerator":["49"],"Ice maker (free standing)":["49"],"Home phone (unlimited)":["49"],"TV Protection (Flat screen up to 60 inches)":["99"],"PC Protection (laptop or desktop)":["49"]}</p>
There's <p> at the beginning and </p> at the end. This is not valid JSON. You need to fix the server script so that it doesn't print anything other than the JSON (whitespace is OK, that's it).
1.confirm that /get-data.html is the correct relational url for your file location.
If you navigate directly to the /get-data.html, does it produce the results that you are after.
try running the same code without , 'json' and see if it works.
hope this helps
Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>