Calling a Python script from Javascript, both local files - javascript

I'm trying to run a python script from a local javascript file (part of a locally running HTML/javascript program).
I've been googling this for hours and found a lot of solutions, none of which actually work for me.
Here is the javascript:
$.ajax({
type: "POST",
url: "test.py",
data: { param: " "}
}).done(function( o ) {
alert("OK");
});
The test.py file is in the same folder as the script/html file.
here is the script:
#!/usr/bin/python
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write('''\
def print_success():
print "sucesss"
''')
print 'Execution completed.'
MakeFile("bla.txt");
It works fine when run normally.
On my Firefox console I get a "not well formed" error and the script doesn't create a file. However, I can see that Firefox does fetch the script, as I can view it in my browser by clicking the file name.

In order for the python script to execute it has to be deployed by a web server that supports it via CGI or WSGI, etc.
Check out the docs here: webservers

There are three problems with your code.
First, when you call $.ajax(), it tries to parse the response as either JSON or HTML. To prevent it, use dataType: "text".
$.ajax({
type: "POST",
url: "111212.py",
data: { param: " "},
dataType: "text"
}).done(function( o ) {
alert("OK");
});
Second, fetching a local file from javascript may violate the Same Origin Policy, depending on the browser. See: Origin null is not allowed by Access-Control-Allow-Origin
An most important, fetching does not execute a file, it just reads it and returns as a string.

So apparently, as has been pointed out, this can't be done, not like this. So I'm going to start a simple CGI python sever to server the HTML file, and execute the script. I've tested it and it works great!

Related

Python code not being executed with Ajax get request

I have this python code:
from twilio.rest import Client
account_sid = "myID"
auth_token = "myAuth"
client = Client(account_sid, auth_token)
client.api.account.messages.create(
to="+num1",
from_="num2",
body="Hello there!")
and when I execute it on the command line python file.py everything works fine,(aka a text is sent to my phone) but I want to execute this code from a javascript file and I am doing this:
$.ajax({
type: "GET",
url: "file.py",
}).done(function( o ) {
console.error("WOW")
});
but the python is not being executed although I do see the console error. I'm not too sure whats going on, I'm wondering if this needs to be changed to a POST request, but that simply gives me a 404 not found error.
I don't think we can give a python filename as url value. AJAX will send a request to the server and in order to handle that request we will need a server side scripting language.
Below link explains how to handle AJAX request in Django.
How do I integrate Ajax with Django applications?

Wikipedia API. File not found Error

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

Running CGI Python Javascript to retrieve JSON object

I want to use javascript to retrieve a json object from a python script
Ive tried using various methods of ajax and post but cant get anything working.
For now I have tried to set it up like this
My Javascript portion:
I have tried
$.post('./cgi-bin/serverscript.py', { type: 'add'}, function(data) {
console.log('POSTed: ' + data);
});
and
$.ajax({
type:"post",
url:"./cgi-bin/serverscript.py",
data: {type: "add"},
success: function(o){ console.log(o); alert(o);}
});
My Python
import json import cgi import cgitb cgitb.enable() data = cgi.FieldStorage()
req = data.getfirst("type") print "Content-type: application/json"
print print (json.JSONEncoder().encode({"status":"ok"}))
I am getting a 500 (internal server error)
Have you tried doing just
print (json.JSONEncoder().encode({"status":"ok"}))
instead of printing the content-type and a blank line?
Have you checked your host's server logs to see if it's giving you any output?
Before asking here, a good idea would be to ssh to your host, if you can, and running the program directly, which will most likely print the error in the terminal.
This is far too general at the moment, there are so many reasons why a CGI request can fail ( misconfigured environment, libraries not installed, permissions errors )
Go back and read your servers logs and see if that shines any more light on the issue.

JQuery ajax GET request to URL fails although HTTP status is 200 OK

I apologize if this question has already been answered.
I am trying to retrieve data from a REST web service that exposes a JSON interface using jQuery .ajax call.
When I call the service using the URL, the jQuery call fails although I get a HTTP status code 200 OK.
When I copy the response into a file on the filesystem and retrieve this, the same call works.
Both the file I am accessing and the web service I am calling are on the same machine.
Some notes on the url used in the code below:
Using:
url: "http://localhost:9090/app/user/861",
the call fails, goes into .fail on all browsers.
The URL itself returns the json on all browsers:
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
when using "test.json" in the local filesystem following is the behavior:
url: "ajax/test.json",
On Firefox, the call executes, goes into .done and displays the result on page.
On Chrome, the call fails with status 404 and the following message -
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I tried different combinations changing dataType:"jsonp", adding a ?callback=? to the end of the URL, and enclosing the data in the test.json with a '(' and a ')' without luck.
Please understand I am new to UI programming, javascript and jQuery.
Please help with what I am doing wrong. Here's the javascript:
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url:"ajax/test.json",
// the following commented call fails, goes into .fail
// url:"http://localhost:9090/app/user/861",
contentType: "application/json",
accepts: "application/json",
dataType: "json"
})
.done(function(data) {
alert("Success");
console.log(data);
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
})
.fail(function(data) {
console.log(data);
alert("Failed");
})
.always(function() {
alert("In Always");
});
});
</script>
The following is the output when I paste the url into the browser (also the contents of ajax/test.json):
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
Your problem is not about UI programming, it's about the security model of modern browsers :p
Access-Control-Allow-Origin errors occurs when you call a webservice (ie: load a JSON file) from a domain that is different from the one hosting your HTML page.
In your case, you are opening the html file from your hard drive (file:///) and calling a webservice on localhost.
This is a security feature in all modern browsers that forbid getting data from a foreign webservice without the webservice owners authorizing you (or everyone, wildcards are allowed) to call it.
I recommend reading the following guide from MDN, so that you understand WHY you are having this problem.
It will then be easy to resolve
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
If you control the source code of the webservice, or the webserver hosting it, you need to add Access-Control-Allow-Origin HTTP headers.
Do you make your ajax call using Apache on wamp, lamp, xampp or mamp or not? I think you work directly using some files lets say on your desktop and not from the www file of wamp. If the browser sends a correct url then the backend responds great, your frontend code seems fine so i think chrome complains about your not using localhost. Am i right? Whats your local development setup?
If it's a local file on the client-side, use file:/// to prefix the URL:
url: 'file:///ajax/test.json'
The third / in file:/// indicates:
As a special case, can be the string "localhost" or the empty
string; this is interpreted as `the machine from which the URL is
being interpreted'.
3.10
Reference here
Download a tool called fiddler, from http://fiddler2.com/ great way to debug web requests and to see why they are failing.
This will help you narrow down the issue you are experiencing and we can help you further because currently its all guess work.
I had the same issue, all worked fine in I.E and FireFox, a had one ajax call to a rest service using jsonp and it worked fine in chrome, however when I tried to load a file using jsonp I got the cross domain error. In short i had to add "file:" to my file path in the url
$.ajax({
type : 'GET',
url : 'file:jsondata/rain_acc_data.json',
dataType : 'jsonp',
jsonpCallback : "jsoncallback",
success : function(data) {
aler('ok');
},
error : function(jqXHR, status) {
alert("Failed to load list" + status + jqXHR);
}
});
this worked for me, make sure to wrap your json in the file with jsoncallback("your jason here");

How to parse XML from another server using JavaScript or jQuery?

I am new to Javascript. I need to parse XML using javascript or jQuery which is another server. I tried by using the below code. But when I executed it, it was not going to success method.
I was able to parse the XML which is in the same folder. Is it possible in javascript to access content from another server. I read the Same Origin Policy.
I was able to get the success message, but cant get the xml data
$.ajax({
type: 'GET',
url: 'http://10.47.5.69/myxml.xml',
dataType: "xml",
success: function(data){
alert('success');
$(data).find("Node").each(function() {
alert($(this).find("element").text());
});
},
error: err
});
function err(xhr, reason, ex)
{
alert('xhr.status: ' + xhr.status);
alert('ex "'+ex);
}
You cannot load something from another server due to cross-domain security checks.
However for javascript, there is a workaround: the JSONP technique: http://en.wikipedia.org/wiki/JSONP
It is used for JSON data but it can just as well be used for any string data. But it will only work if you have some degree of control (i.e. can install a script) on that server.
Another alternative is to proxy that URL on your own server. That might be easier.

Categories

Resources