How to respond to an XMLHttpRequest - javascript

I'm using a Javascript to ask our app (which is in Google App Engine) if the file a user wants to upload is already in his list of files (he will overwrite).
I know how to send the request, but how can I create a response from the server, using Python?
This is the request:
var req = new XMLHttpRequest();
req.open('POST', 'https://safeshareapp.appspot.com/upload', async);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", body.length);
req.setRequestHeader("Connection", "close");
if (async) {
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var response = null;
try {
response = JSON.parse(req.responseText);
} catch (e) {
response = req.responseText;
}
callback(response);
}
}
}
// Make the actual request
req.send(body);
As you see, we are getting the responseText from the request after everything has gone OK, but my question is how do we fill that responseText field on the server side??

class MyRequestHandler(webapp.RequestHandler):
def get(self):
import json
result = {"filename": xxx} // just an example, result can be any Python object
json_obj = json.dumps(result)
self.response.out.write(str(json_obj))

Related

AttributeError: 'NoneType' object has no attribute 'get' //500 (Internal Server Error)

this is not sending any data from crome extension,i am trying to send json string to the server with mentioned url which says none type object has been returned,
var xhr = new XMLHttpRequest();
var ur = "http://127.0.0.1:8080/animal";
var dat = {"subject":"subject"};
xhr.open("POST", ur, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(dat);
}
};
xhr.send(dat);
You can't send an object with xhr.send(), you need to serialize it.
var dat = 'subject=subject';

Writing Request Payload property on httprequest

I am trying to develop a browser extension that will help people to some stuff way easier.
One of the things that I need to do is sending couple of http requests.
I need to recreate requests that site makes when doing certain things.
Now site uses Request Payload which is my first time using(used form data),therefore I don't know how to make Request Payload same as when site sends request.
var request = new XMLHttpRequest(),
url = 'https://www.hidden.com/api/v1/tipuser/',
data = 'steam_64=76561198364912967&tip_asset_ids=[]&tip_balance=0',
token ='...';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'text/plain');
request.setRequestHeader('authorization', token);
request.send(data);
This is my code and after sending it you can see how my Request Payload looks.
I have been having difficulties for days now and I searched online but couldn't find solution to this.I know that I just have to write it differently .
This is site's request
This is my request
Cheers!
Could you try sending your request as application/json and build your data object like in the example below?
Your Content-type request header should be application/json
var request = new XMLHttpRequest(),
url = 'https://jsonplaceholder.typicode.com/posts/',
data = {
steam_64: '76561198364912967',
tip_asset_ids: [],
tip_balance: 0,
token: '',
};
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json');
request.setRequestHeader('authorization', data.token);
request.send(JSON.stringify(data));

Getting an Access Token with Xml HTTP Request

I am having some trouble getting an access token from a site for a web application. The response to the following is
"{"error":"invalid_request","error_description":"The grant type was not specified in the request"}".
I have specified the grant type below but it seems I have not formatted the request correctly.
Any suggestions?
var getToken = new XMLHttpRequest();
getToken.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
getToken.open("POST", "https://api2.libcal.com/1.1/oauth/token", true);
getToken.send('grant_type=client_credentials','client_id=XXX', 'client_secret=XXXXXXXXXXXXXXXXXXXX');
As you are doing a Post Request to get an access token , the parameters should be send in the body (JSON) like below : (I tested ,it works fine )
// form data for the post request
var data = {
"grant_type":"client_credentials",
"client_id": "XXX",
"client_secret": "XXXXXXXXXXXXXXXXXXXX"
};
// construct an HTTP request
var getToken= new XMLHttpRequest();
getToken.open("POST", "https://api2.libcal.com/1.1/oauth/token", true);
getToken.setRequestHeader('Content-Type', 'application/json');
// send the collected data as JSON
getToken.send(JSON.stringify(data));

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

access XMLHttpRequests send(data) in PHP backend

I have an XMLHttpRequest sending data to a PHP backend.
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send('query=messages'); // <-- i want to access this in php
i tried
print_r($_GET) and print_r($_REQUEST) but neither works.
anyone knows how to access this data?
You can only send data through the XMLHttpRequest.send()-method for POST-requests, not GET.
For GET-requests, you need to append the data to the url as query string.
url += "?query=message";
Then you can retrieve the data with PHP using:
$message = $_GET['query'];
More info: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Categories