How to set multiple HTTP headers in JavaScript get () method - javascript

I have been searching the total Internet from around a week and finally decided to post here. I want to send an HTTP get request to an API with two headers for authentication. These are custom headers and need to be sent at once.
I have tried the following code but it never gives me success. The API returns a JSON file which will have parameters like "title", "description". The URL and headers work fine, when I tried it using hurl.it.
This is the code. Please suggest some answer to solve this problem. And one more thing is, I want to do it using JavaScript only, no jQuery, AJAX, or AngularJS.
var xmlhttp = new XMLHttpRequest();
var url = "https://affiliate- api.flipkart.net/affiliate/offers/v1/dotd/json";
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 &&xmlhttp.status==200) {
var myArr = JSON.parse(xmlhttp.responseText);
function display(arr) {
var i;
var out = " ";
for(i = 0; i < arr.length;i++) {
out += "<p>title:" + arr.dotd[i].title + "<br>description:" + arr.dotd[i].description + "<br></p>";
}
document.getElementById("p1").innerHTML = out;
}
}
else {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Fk-Affiliate- Token","xxxxxxxxxxxxxxxxx");
xmlhttp.setRequestHeader("Fk-Affiliate-Id","xxxxxxxxx");
xmlhttp.send();

Related

Why is my XML Http request not executing anything?

I have a XML http requests but for some reason it doesn't work. It is supposed to check the number of friends the person has then if there aren't enough displayed you know, do all that stuff. And don't worry, I checked the database and all the sql, it removes/adds friends successfully but the problem is that the console says it executes it but the function doesn't do anything
Here is the function :
x = document.getElementsByClassName("numoffriends");
numoffriends = x.length;
var fullurl = "../backend/friends.php?numoffriends=" + numoffriends + "&loadfriends=true";
var request = new XMLHttpRequest();
request.open("GET", fullurl , false);
request.onload = function(){
if(request.status == 200){
let testdivvv = document.createElement("element");
testdivvv.innerHTML = this.responseText;
groupchat = document.getElementById("leftsmallbox");
groupchat.append(testdivvv);
}
}
request.send();
}
setInterval(loadfriends, 1500);
If it makes any difference there are also 4 other functions on the same timing i.e gets executed. I checked, there is indeed an object called leftsmallbox.
If you have any questions just ask, I'll be available for a while

How to fill an Array with response of an http request?

I want to fill a JavaScript array with a few objects, caught by an http request. Unfortunatly I don't know which ArrayMethod I should use. I tried splice(), but it seems like it doesn't accept variables (for the http output) as an input. Is there anybody who has some tips or knows how to do it?
In my code example I want to fill the Array with the content, shown in "id01".
Thanks for your help!
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://waterfallexpress2020.s3.eu-central-1.amazonaws.com/myTutorial.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
return out;
}
var test =[];
test.splice(0,0,myFunction); //DOESN'T FILL MY ARRAY WITH THE OUTPUT OF myFunction()
document.write(test);
</script>
You made an asynchronous request, so you will have to wait for response. You did it with the xmlhttp request and the statement myFunction(myArr).
So in order to keep this returning response, you should initiate variable before your request and fill it with the response:
var test;
...
xmlhttp.onreadystatechange = function()
...
test = myFunction(myArr);
...
document.write(test);
Be careful with splice, it create new instance of initial variable and it losts getters and setters.

PubSub.js multiple subscriptions, or a different way to handle awaiting on multiple callbacks

I am trying to figure out the best way to handle this scenario. Basically I want the flow to work like this:
1.) Get configuration data from server (async)
2.) Run doStuff() after configuration data is received (async)
3.) Run postResults after doStuff() completes
Currently I seem to have this flow working using PubSub.js, however I am trying to figure out how I can provide the results from config data (#1) to postResults (#3). While I seem to have the flow working with PubSub, I'm not sure how to access the configuration (#1) callback data from postResults (#3)
Here is a code summary:
PubSub.subscribe('config', doStuff());
fetchConfigurations();
function fetchConfigurations () {
var req = new XMLHttpRequest();
var url = CONFIGURATION_SERVER_URL;
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var configObject = eval('(' + req.responseText + ')');
PubSub.publish('config', configObject);
} else {
console.log("Requesting config from server: " + url);
}
}
req.open("GET", url, true);
req.send(null);
}
function doStuff() {
PubSub.subscribe('results', postResults);
var results = {};
// do some async work...
results['test1'] = "some message";
results['test2'] = "another message";
PubSub.publish('doStuff', results);
}
function postResults (doStuffId, doStuffData) {
var req = new XMLHttpRequest();
var url = TEST_RESULTS_URL; // I want to get this from the configObject is get in fetchConfigurations
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send(doStuffData['test1'] + doStuffData['test2']);
}
Using promise seemed like the a better fit for this problem instead of pub/sub, here is the implementation I ended up using:
https://github.com/hemanshubhojak/PromiseJS

No response when using AJAX and JSON

function getIDs() {
alert("1");
var title = document.getElementById('title').value;
alert(title);
title = "http://www.imdbapi.com/?i=&t=" + title;
alert(title);
xmlhttp=new XMLHttpRequest();
alert("2");
xmlhttp.open("GET",title,true);
alert("3");
xmlhttp.send();
alert("4");
var imdbData = xmlhttp.responseText;
alert(imdbData);
var imdbJSON = JSON.parse(imdbData);
//document.getElementById('title').value = imdbJSON.Title;
alert(imdbJSON.Title);
document.getElementById('imdbid').value = imdbJSON.ID;
return true;
}
I'm trying to fetch the ID of a film based upon it's title, the function gets called successfully and the alerts are correct until the alert which returns "imdbData", which returns a blank alert, then no more alerts occur, I'm unsure where I'm going wrong here. Any assistance would be appreciated.
You're opening it asynchronously. To make it synchronous, change this:
xmlhttp.open("GET",title,true);
To this:
xmlhttp.open("GET",title,false);
A usually-considered-better way would be to make it work with asynchronicity:
function getIDs() {
alert("1");
var title = document.getElementById('title').value;
title = "http://www.imdbapi.com/?i=&t=" + title;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
var imdbData = xmlhttp.responseText;
var imdbJSON = JSON.parse(imdbData);
document.getElementById('title').value = imdbJSON.Title;
document.getElementById('imdbid').value = imdbJSON.ID;
}
};
xmlhttp.open("GET",title,true);
xmlhttp.send();
return true;
}
Additionally, you cannot request pages from other domains. You may need to switch to JSONP if the API you're using supports it, or use your web server as a proxy.
You are not allowed to do cross site scripting with JavaScript which is why you get nothing in return.
You need to be on the same domain as you post your AJAX call to.
Use a serverside script to parse the URL for you instead.

How to get JSON object in Servlet from JSP?

In JSP page I have written:
var sel = document.getElementById("Wimax");
var ip = sel.options[sel.selectedIndex].value;
var param;
var url = 'ConfigurationServlet?ActionID=Configuration_Physical_Get';
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
httpRequest.open("POST", url, true);
httpRequest.onreadystatechange = handler(){
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
param = 'ip='+ip;
param += 'mmv='+mmv;
param += "tab="+tab;
}};
httpRequest.send(param);
I want this param variable in my ConfigurationServlet. Can anyone tell me how to get this json object in servlet?
Update: I changed my statements and now it is showing status code as 200.
var index = document.getElementById("Wimax").selectedIndex;
var ip = document.getElementById("Wimax").options[index].text;
httpReq = GetXmlHttpObject();
alert(httpReq);
var param = "ip=" + ip;
param += "&mmv=" + mmv;
param += "&tab=" + tab;
alert("param "+param);
var url="http://localhost:8080/WiMaxNM/ConfigurationServlet?ActionID=Configuration_Physical_Get";
url = url+"?"+param;
httpReq.open("GET",url,true);
alert("httpReq "+httpReq);
httpReq.onreadystatechange = handler;
httpReq.send(null);
But new problem has occured. Control is not at all going to the servlet action ID as specified in url. Please tell me what is wrong here.
The code in the handler will only be invoked AFTER the request is been sent. You need to populate param before this. You would also need to concatentate separate parameters by &.
Thus, e.g.
// ...
httpRequest.onreadystatechange = handler() {
// Write code here which should be executed when the request state has changed.
if (httpRequest.readyState == 4) {
// Write code here which should be executed when the request is completed.
if (httpRequest.status == 200) {
// Write code here which should be executed when the request is succesful.
}
}
};
param = 'ip=' + ip;
param += '&mmv=' + mmv;
param += "&tab=" + tab;
httpRequest.send(param);
Then you can access them in the servlet the usual HttpServletRequest#getParameter() way.
That said, the Ajax code you posted there will only work in Microsoft Internet Explorer, not in all the four other major webbrowsers the world is aware of. In other words, your Javascript code won't work for about half of the people in the world.
I suggest to have a look at jQuery to lessen all the verbose work and bridge the crossbrowser compatibility pains. All your code could be easily replaced by
var params = {
ip: $("Wimax").val();
mmv: mmv,
tab: tab
};
$.post('ConfigurationServlet?ActionID=Configuration_Physical_Get', params);
And still work in all webbrowsers!
Update: as per your update, the final URL is plain wrong. The ? denotes a start of the query string. You already have one in your URL. You should use & to chain parameters in the query string. I.e.
url = url + "&" + param;

Categories