Add header to http request - javascript

My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.
That's the code I'm using:
function btn_OnTouch(){
var url = "myurl";
SendRequest(url);
}
//Send an http get request.
function SendRequest(url){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
HandleReply(httpRequest);
};
httpRequest.open("GET", url, true);
httpRequest.send(null);
app.ShowProgress("Loading...");
}
//Handle the servers reply (a json object).
function HandleReply(httpRequest){
if (httpRequest.readyState == 4){
//If we got a valid response.
if (httpRequest.status == 200){
txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
}
//An error occurred
else
txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);
}
app.HideProgress();
}
The told me I should probably include the headers like this, but I don't know where to put them in my code.
httpRequest.setRequestHeader(“username”, “myuser”);
httpRequest.setRequestHeader(“password”, “mypass”);

You need to do it just after calling the open method like this:-
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);

Related

REST API get call with credentials

I have trying to call ServiceNow API from a SharePoint hosted adding i'm working on using JavaScript with credential for the header. But when i try to run it during the run time the request gets an error. Any help regarding this would be highly appreciated.
var req = new XMLHttpRequest();
req.open('GET',Servicenow_URL, true);
req.setRequestHeader('Content-Type', 'application/json');
req.open("Authorization", "Basic " + btoa(Username + ":" + password));
req.withCredentials = true;
req.send();
alert("here1");
if (req.readyState === 4) {
if (req.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(req.responseText);
alert("here2");
} else {
console.error(req.statusText);
alert("error");
}
}
the developer tool from browser shows the error as "the server responded with a status of 501"

ESP8266 not receiving HTTPRequest

I can't seem to receive Javascript's HTTPRequest. I get this HTTP/1.1 200 OK
but I cannot seem to get the URL that I sent over. I just want the link that I am sending over on my webpage.
Here is my javascript:
jQuery(function($) {$("button").click(function(){
console.log(this.id);
document.getElementById("direction").innerHTML = this.id + " is pressed.";
newurl = 'index.php?btn='+ this.id+"?key="+user.key;
sendHttpRequest(newurl);
});
});
function sendHttpRequest(update){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
xhttp.open("GET",update,true);
xhttp.send(null);
console.log(update);
}
ESP8266 in void loop:
WiFiClient client;
String url = "/index.php?";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Request Sent");
String request = client.readStringUntil('\r');
Serial.println("headers received");
Serial.println(request);
You're only reading the first line of the response from the index.php script on the ESP, which will generally be the HTTP status code you are seeing, and nothing else (Unless there's some other code you haven't posted). You need to read the entire HTTP message to get the response, specifically the body - Assuming index.php uses the body to return the data you need. You can find a description of the HTTP message structure here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html

make a post request in js and open its results in a new window

I have a js file, containing a folder myFunc(phone_number)
Now when this js function is called, I want to make a POST request to the URI https://pay.something.in:443/FetchPhone/ passing the json {'phone_number' : 10 digit phone no. } as input to the request
and show its output in a new window.
Can somebody tell me how do I do that?
Seems to me like you want to make a POST request with xhr.
var xhr = new XMLHttpRequest();
xhr.open('POST', "https://pay.something.in:443")
xhr.setRequestHeader("Content-type", "application/json");
xhr.send( '{"phone_number" : 4455566677 }' );
xhr.onreadystatechange = function(){
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
alert('HTTP error ' + req.status);
return;
}
console.log(xhr.responseText);//this is your response
window.sessionStorage['response'] = xhr.responseText;
window.open('Your window');//The data is accessible through sessionStorage.
}

Send Custom HTTP Body with AJAX POST request

How do I send a custom HTTP body with my POST AJAX request in plain Javascript (not JQuery)? I am actually trying to send a JSON file in the body. I can set the custom header fields but can't find how to set HTTP body.
below is the code
function calculateorder() {
document.getElementById("finalize").style.display = "inline";
url1 = "https://ethor-prod.apigee.net/v1/stores/";
url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";
url = url1 + store_id + url2;
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(calculate));
}
When I used the same headers and JSON file with Rested (a OSX HTTP client) It works perfectly
Add parameter in XmlHttpRequest Obeject's .send() method
Like this:
xhr.send('username=me');
Send JSON Format Data myData Like this:
xhr.send(JSON.stringify(myData));

Classic Ajax being canceled during an ajax request

function submitLogin(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var testlabel = document.getElementById('testlabel').value;
var postStr = "username=" + username + "&password=" + password + "&testlabel=" + testlabel;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('mainPage').innerHTML = xmlhttp.responseText;//ATTENTION1
} else {
document.getElementById('mainPage').innerHTML = "Logining......";//ATTENTION2
}
}
xmlhttp.open("POST", "loginto.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(postStr);
}
These are my codes.
If I change the "mainPage" into something else in the //ATTENTION2, the page will auto send a "GET" method, but if I still use the "mainPage" in there, there will be no problem.
However, if I change the "mainPage" into something else in the //ATTENTION1, there will have no problem with the post method, the response things can be shown in the correctly.
So, is there any solution? Thanks!
What does "something else" mean ? You need to have an id of an element in your page, where the content from the ajax response will be rendered.
For example, if you have a
<div id="myID"></div>
somewhere in the page, and change 'mainPage' in //ATTENTION1 to 'myID', then the response from the ajax request will be placed in that div.
The change you make in //ATTENTION2 is for intermediary states because it is on "else", so will not impact what happens when the ajax request is complete.

Categories

Resources