Currently I'm using this function to send my JSON from a chrome extension. This is the client code from javascript sending the data.
function callPython(){
var url = 'http://AWS_IPNUMBER/';
var data = {'bob':'foo','paul':'dog'};
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json',
success: function(data){
var jsonObj = $.parseJSON(data);
alert(jsonObj.encPassword);
},
failure: function(errorMsg) {
alert(errorMsg);
}
});
}
This is the server code for Python:
s = socket()
s.bind(('', 80))
s.listen(4)
ns, na = s.accept()
while True:
try:
data = ns.recv(8192)
except:
ns.close()
s.close()
break
data = json.loads(data)
print data
The problem is that although it is listening, data is empty at data = ns.recv(8192). Then data = json.loads(data) doesn't work since data is empty. Why is this? I thought it may be a problem with my security group on AWS but if I go to http://AWS_IPNUMBER/ I get the header from the browser while running the python script.
You may have better luck with a good framework like tornado or django.
I say this because in your code you are trying to parse an http POST with json.loads. HTTP isn't that simple. You will need to deal with the request and headers before you get to the body, and this can be spread out across multiple packets. Why try to reinvent the wheel when you can setup a standards compliant server from a well established project.
The data that $.ajax function will put is a complete HTTP request, which json.loads() won't understand. In this case you need to instantiate a HTTP server which will process the HTTP requests and then process the HTTP payload with json.loads().
Related
I have a website with a big form. When I first made the website, I was using a GET request to send the form values to a Python CGI script (using the JavaScript fetch function). In the Python script, I could read the data with parameters = cgi.FieldStorage().
Since a GET request has a limited payload size, I had to switch to a POST request because that request type has no limit.
I changed my JavaScript fetch function to the following to make a POST request:
fetch('../../cgi-bin/saveFormAnswers.py', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(antwoord => antwoord.json())
.then(data => {
console.log("Return data Python:")
console.log(data);
}
);
However, I can't seem to get the data in the Python CGI script. cgi.FieldStorage() doesn't work anymore. How do I get the POST payload in the Python script and how do I send a (JSON) dictionary back as a response to the POST request?
I'm not using any frameworks like Flask.
EDIT: I came to the conclusion it's related to the JavaScript code and that cgi.FieldStorage() should work. Instead of letting JavaScript do the POST request, I set up the POST request directly in the HTML form which worked just fine without any issues. I'm still trying to figure out what's wrong with my JavaScript code.
Fixed it by using sys.stdin instead of cgi.FieldStorage().
data = ""
if int(os.environ.get('CONTENT_LENGTH', 0)) != 0:
for i in range(int(os.environ.get('CONTENT_LENGTH', 0))):
data += sys.stdin.read(1)
I am having issue with extracting the data from the response received by api call
http://open.pkfare.com/apitest/shopping?param="+json_encoded_string
where json_encoded_string is base64 encrypted json data, which is done as per the documentation in http://open.pkfare.com/documents/show
As per the documentation the response received will be in gzip format,
I'm facing issue with retrieving this data to json format. I'd gone through many blogs for the solution but i didn't got the solution and finally end up here
I'm calling this api using ajax call
var fbURL = "http://open.pkfare.com/apitest/shoppingparam=" + json_encoded_string;
$.ajax({
url: fbURL,
type: 'GET',
success: function (resp) {
//---i need code for reading the received gzip data here---
},
error: function (e) {
alert('Error: ' + e);
}
});
As you are using AJAX post to get this, I will recomond to use server-side language to do it. I think this is the best and only way for it to actually work.
Post your AJAX request to a server side language then there call the api and do your other coding to parse the data.
Recently i am learning json to create apps.I have a doubt in a Json , php based chat system .
In this , the code work fine for same origin policy.But for sending and receiving data from external url, it successfully sends data to external php.But not receiving any data from server.I search in internet to solve this problem , and found jsonp as alternative. I tried jsonp , but i m not sure if am correct because i am new to ajax itself.
Please don't mis understand my question.I want to load a index.html file from localhost , when i send request to external url (anysite.com/xx/ajax.php) .It process and returns the data back to index.html.But the problem is my data is sended finely and processed on the server but it doesn't return to remote file.But it works fine for same server.
$.tzPOST = function(action,data,callback)
{
$.post('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
please help me with a code.
You cant receive JSON from external web by JavaScript, because of the policy.
But you can do AJAX request on your PHP file and there you can get the JSON by file_get_content http://cz2.php.net/file_get_contents function.
For using(working) with jsonp, u can take ready solution jquery-jsonp
from GitHub.
Example of using (by you question):
$.tzGET = function(action,data,callback){
var url = 'http://anysite.com/xx/ajax.php?action='+action;
$.jsonp({
type: 'GET',
url: url,
callbackParameter: callback,
dataType: 'jsonp',
data: data,
timeout: 10000,
success: function(json){
alert('success')
},
error: function(){
alert('error')
}
});
I have seen this topic: ajax request to python script where they were trying to do exactly what I need but there is one information missing.
$.post('myPythonFile.py',{data},
function(result){
//TODO
}
);
Now my problem is: how do I call a certain function which is inside myPythonFile.py? Is there a way to specify the name of the function and to give it my input data?
Thank you very much for your time.
Ajax calls making HTTP requests,so you need to have a HTTP server which handles your requests as it is seen in the other question. (There is CGI which provide HTTP request handling). In Python you can use DJango, Bottle, CGI etc to have HTTP request handling. to call python function from javascript.
Edited :
in your url.py you should define your api url;
(r'^myAPI', 'myAPI'),
and on this url you should have a web API in views.py. It can be like ;
def myAPI(request):
callYourFunction();
and you can call it from Javascript now. You can use JQuery for AJAX request;
$.ajax({
type:"GET",
url:"/myAPI",
contentType:"application/json; charset=utf-8",
success:function (data) {
},
failure:function (errMsg) {
}
});
The HTTP method type does not matter, if you only wanna run a Python script. If you wanna send data from javascript to Python you can send the data as JSON to Python as POST method.
Edite: refined the code according to advice in comments but still no luck
Update: thanks ThiefMaster after following your advice I found a bug in my view function but after fixing it now I get in django debug
Forbidden (403)
CSRF verification failed. Request aborted. Help Reason given for
failure:
CSRF token missing or incorrect.
I trying to use jquery ajax to send json data to django
here is my js code
$("#send").click(function () {
var events = $('#calendar').fullCalendar('clientEvents');
console.log(events);
var filter = [];
filter[0] = 'start';
filter[1] = 'end';
filter[2] = 'title';
events = JSON.stringify(events, filter, '\t');
console.log(events);
$.ajax({
type: "POST",
data: {events: events},
url: <my_url>,
});
});
on chrome devtool every thing is ok until the last $.ajax()
it throw this error
Failed to load resource: the server responded with a status of 403 (OK)
If any one can figure out what I'm doing wrong please go ahead
thanks in advance
data: "events" should be data: events. Your server might not like a non-json payload.
You also want to add contentType: 'application/json' since you want to post json, not form-encoded values. If you do expect form-encoded values on the server-side though, use data: {events: events} to get a POST data field events containing the JSON string.
I found the other part of the solution about Forbidden 403 regarding csrf
in this page of Django docs
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax