XMLHttpRequest POST API Call - javascript

Need help to find out why am I not getting any responseText back? I run this same API call on REST client with same parameters and I get response back fine but not through code. SignedToken is JWT token which should be sent in body.
var xapicall = new XMLHttpRequest();
xapicall.open("POST",'https://example.com/initauthn/do',true);
xapicall.setRequestHeader('Content-type', 'application/json');
xapicall.onload = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xapicall.send(signedToken);

Related

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));

Return WebMethod Response & Use If Statement To Alert User Based On Response

I'm trying to include an if statement that analyzes the webmethod response which is either true or false. I just want to alert the user the post was successful if the response is true or the post was not successful if the response is false.
I can get the response using xhttp.responseText but I can't figure out how to build that into an if statement inside my javascript below:
//JavaScript that Posts to WebMethod
<script>
function createNewComment() {
var xhttp = new XMLHttpRequest();
var url = "http://localhost:57766/PALWebService.asmx/insertComment"
var a = document.getElementsByName("existingguid")[0].value;
var b = document.getElementsByName("newcomment")[0].value;
var c = 'existingguid=' + a + '&newcomment=' + b;
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.send(c);
}
</script>
I figured it out. After checking that readyState was 4 and status was 200 I simply nested another if statement to check the responseText from the XMLHttpRequest and it was true I called another function and if it was false I notified user the post failed on the webmethod. It may not be perfect, but it works for what I need.
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText = true) {
addComment(b, today, userName);
}
else {
document.getElementsByName("newcomment")[0].value = '';
$("#commentLabel").html("Your comment was not saved in the database. Please try again or contact system admin.");
}
}
};

Send data on ajax

Is this the correct way to send data to server on ajax request?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(response);
}
};
xhttp.open("GET", "https://myurl/", true);
xhttp.send(JSON.stringify("{ action: 'search', mode: question}"));
Because I get this error 405 (Method Not Allowed - Action not found)
No, there are several issues with that:
alert(response); will fail because there's no response variable; you'd probably want alert(xhttp.responseText).
You're doing a GET, but then trying to send a POST body. You can't do that. GET information is in the URL, not the body.
You're sending JSON (well, trying to), but not identifying it as JSON.
You're passing a string into JSON.stringify, where normally you'd pass an object, not a string, as its job is to convert things to JSON strings.
Assuming you mean to do a POST, and you really do want to send JSON (e.g., that the server is set up to accept JSON from the client), then minimal changes would be:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xhttp.responseText); // 1
}
};
xhttp.open("POST", "https://myurl/", true); // 2
xhttp.setRequestHeader("Content-Type", "application/json"); // 3
xhttp.send(JSON.stringify({ action: 'search', mode: question})); // 4
Note that I'm assuming question is an in-scope variable in that.

XMLHttpRequest doesn't send some headers

The title explains my problem clearly. I am testing the AJAX requests of my application but I cannot send some headers, for example Authorization header.
For testing I use this endpoint to echo me the headers I sent. Here is my javascript code:
var loadDoc = function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(JSON.parse(this.responseText));
};
}
xhttp.open("GET", "http://headers.jsontest.com/", true);
xhttp.setRequestHeader("Authorization", "JWT token");
xhttp.send();
}
I can send the exact same request with python's requests module. But I can't send it with XMLHttpRequest. XMLHttpRequest can send the Content-Type header and the server echoes me the headers but not Authorization.
What is going on here?

Categories