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)
Related
I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there.
This is my Post-Function (which is called by clicking on a button):
function answer(){
let data = {
name : $('#send').val()
};
console.log(data);
$.ajax({
type: 'POST',
url: 'http://localhost:3456/MyWebApp/Test',
dataType: 'text',
data: data.name,
success: console.log('post was successfull'),
error: function(textStatus, errorTrown){
console.log(textStatus + " " + errorTrown);
}
});
}
On my Server I try to collect the data with the following function:
app.post('/MyWebApp/Test', function(request,response){
console.log(request.body.data);
});
app.listen(3456);
My problem is, that the value on my server (in the above console.log) is always undefined.
I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?
I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.
You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event
request.on("data", callback);
I made a website in python using Django. My site allows you to control lights while indicating if the light is on or not.
I'm looking for a solution that could make a simple request with data to the server and send data back to the client without updating the entire page but only a part of it.
My ideal would be for the client to make a request to the server with identification data. Then, the server returns the updated data that the user is allowed to have.
Is that possible to make a JavaScript to do that ? And the server, how it can return data to the client ?
You can Use jquery AJAX for send request and get a response and Update an element or part of the page you can read more about it in :
W3schools
or :
jquery.com
AJAX function I use for PHP project:(Just for example)
$.ajax({
type: "POST",
url: Url,
data: InfoData, // data if you want to send for example InfoData={dataName: variable} or you can set this = '' if you don't want to send data
datatype: "html",
success: function(result) {
console.log(result);
}
});
I'm trying to fetch data from a website; however, it return a PHP file as text without the result that I look for (the result after enter all required input) after sending out all the information by using 'POST' method to the server
Down here is my code that I used to fetch info:
var form = {
'cp': poke_cp,
'p_id': poke_id,
'hp': poke_hp,
'dust': poke_dust,
'up': "1"
};
$.ajax({
type: 'POST',
url: "https://pokefind.co/ivcalc.php",
dataType: "text",
data: form,
success: function (data) {
console.log(data);
}
});
As said in comments by #icecub, if the remote server does not allow cross origin requests you will not be able to fetch datas from the website.
The page you are trying to POST seems be the page that handle a form. So you have two problems :
CSRF, during the form handle there is a verification to be sure that you come from the form page
Cross Origin possibly not allowed.
If the website has a WebService you should use it.
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().
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')
}
});