Python code not being executed with Ajax get request - javascript

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?

Related

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.

Calling a Python script from Javascript, both local files

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!

Server Code HTTp POST to remote server; Javascript API call

I found an answer to a question that tells what to do, but I don't know how to implement it.
jQuery cross domain POST shenanigans
I'm programming in Django and javascript
Steps:
ajax post to a local URL - How do I do this? Where do I post this to?
Server code will do an HTTP POST to remote server - How do I do this in django?
Send response to JS - I can figure that out.
Thanks
use the $ajax() function from jquery
use urllib and urllib2 to access external resources from python. Call these libraries from within your view function
Here's an example for the $ajax function:
$.ajax({
type: "GET",
url: '/htmlApi/sendSms/',
data: {
'phone':'+12412354135',
},
success: function(data){
$("#ajaxDestination").html(data);
}
});
here's an example of a view function that posts data to the remote server:
def verify1(request):
u = request.session['user']
u.phone_number = request.GET['phone']
u.save()
apiUrl = "http://www.XXXXXXXXX.net/api/send.aspx?username=XXXXXXX&password=XXXXXX&language=1&sender=XXXXXX&mobile=" + request.GET['phone'] + "&message=" + 'ghis' + " is your verification code."
x = urllib2.urlopen(apiUrl).read()
return HttpResponse(x)
(This is an automated sms sending api call)

How I get respone text in application and bind to the label in cross ajax call

I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers

Ajax call from Greasemonkey to a Servlet: response failure

Though I've programming experience, am completely new to GS, JS, or anything related to UI.
Scenario: Making an AJAX call from Greasemonkey script to a Servlet
Greasemonkey/JS Code:
function getResultsData(query){
alert("Getting the Data");
$.ajax(
{
cache: false,
data: {"q":query},
dataType:"text",
url: "http://myserver.com:8000/search?",
success: processData
}); //end of $.ajax }
function processData(data){
alert("Got the data");
var myResultDiv = document.getElementById("searchRes");
myResultDiv.innerHTML = data; }
Servlet Code:
System.out.println("-----------This is an AJAX call------------------");
//Commented the original logic
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("Text from Servlet");
Problem:
GS/JS code works perfectly if the url (in $.ajax) is some other existing API. Response reflects in the UI
However, when I give my server's url, I can observe in the Firebug.Console that there's no http response for that call but the status says 200 OK with the whole entry turned 'RED'.
When I test the url copied from Firebug's 'http call entry', it's working perfectly as I can see the response 'Text from Servlet' on the new tab.
Can someone please help.
NOTE Website on which greasemonkey runs, and my server belong to same domain, i.e.
Greasemonkey website: wwww.example.com
My server: www.myserver.example.com
Thanks to #mattedgod. His comment triggered me to research more and I found the answer.
Add the following snippet to make it work.
response.setHeader("Access-Control-Allow-Origin", "*");
Surprisingly, it doesn't work if I explicitly specify my own server's full http address in the header. I yet to find out why.

Categories

Resources