How do i put headers in an api call? - javascript

I am making an api call to
http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter
I have changed the appropriate information in the URL to reflect the correct host address/port / user id.
When that is complete, the page requests that I log on with a Username and Password.
I can manually enter this information, and receive the XML that I need. This is not Ideal. I would rather have a form that passess in this information.
To my understanding, this information is passed within the "headers". I have tried to look up how to do this, and even attempted using postman without much luck. I am not sure how to do this.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter", true);
xhttp.send();
}
per w3 schools I can use setRequestHeader() which adds a label/value pair to the header to be sent.
I have tried
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter", true);
xhttp.send();setRequestHeader(Username:myUserName,Password:myPassword);
}
with no resolution. once i get this working i will set up the form and pass in the values.

You are using setRequestHeader in the wrong way and calling send before setting headers in any case.
Try with
xhttp.setRequestHeader('Username', myUserName);
xhttp.setRequestHeader('Password', myPassword);
xhttp.send(); // only call send after setting up the headers

xhttp.setRequestHeaders(name, value) and it should be invoked before xhttp.send(). mdn

Related

How to get a certain line from xml from other webpage (url) in js?

const xhrRequest = new XMLHttpRequest();
xhrRequest.onload = function()
{
dump(xhrRequest.responseXML.documentElement.nodeName);
console.log(xhrRequest.responseXML.documentElement.nodeName);
}
xhrRequest.open("GET", "/website_url.xml")
xhrRequest.responseType = "document";
xhrRequest.send();
I'm trying to request a xml page from a page, but i'm unable to get certain line from xml in javascript. Thank you!
You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp
Here is an example function:
function SendRequest(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
// Success
}
};
xmlhttp.open("GET", "example.com", true);
xmlhttp.send();
}
Now, about getting a value from the xml document, you can use .getElementsByTagName(). Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange of the http request
if(this.readyState == 4 && this.status == 200){
let xmlDocument = this.responseXML;
console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
}
So if the xml document had an element like:
<TestTag>Hello</TestTag>
the function would print Hello

How to call REST service using JavaScript?

Using the code I found from one of the StackOverflow postings, I'm trying to call a REST service GET method. However, when the code runs it is not putting the GET format correctly in the URL.
Here's the code:
<!DOCTYPE html>
<script>
function UserAction(json)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
};
xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(json);
}
</script>
<form>
<button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
<label for="json">JSON:</label>
<input type="text" id="json" name="json"><br><br>
</form>
</html>
The expected format of this GET REST service would be:
http://localhost:8080/isJsonValid/json
(where json in the line above is the actual JSON sent as a parameter.)
Yet, what is shown in the URL line includes the project, directory and the URL has the ?name=value syntax.
Since the GET doesn't match the simple http://localhost:8080/isJsonValid/json format, I get a 404 error.
I realize there's something obvious I'm missing.
Thanks to all for suggestions.
If you need to send data you need to either send it as a query param or as the body. If you want to send it as a body need to use POST type. Below is the example of POST type.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach(movie => {
console.log(movie.title)
})
} else {
console.log('error')
}
}
// Send request
request.send()
For post Request. As I don't have any API with me I have used get API URL.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText)
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
Thanks all for the great input and help!
The best solution for me was to just use, as suggested, a POST. The GET was always putting the "?" in the URL even if I concatenated it, That "?" isn't how the REST service interprets the GET parameters so it wouldn't work that way. In the REST framework I'm using, GET parameters are just concatenated with one or more "/" as separators in the URL.
Appreciate all the terrific help here on SO. :)

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.

How to import an xml file with javascript

So i've been googling this for a while now and no solution seems to work for me.
Given that the url to the xml file (taken from valve api) is: playerSummariesXml
I tried ajax calls such as:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp);
}
xhttp.open("GET", playerSummariesXml, true);
xhttp.send();
}
Which returns the link to my website with a /0 appended to the end,
and
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
which says activexObject not declared
And other things...
Is there one resolute way to pull an xml file with javascript from a given url and read/display it?
I'm getting really confused considering this is super easy to do with php and don't see why I can't find a similar thing with javascript.
Can you try the below code,
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp);
}
}
xhttp.open("GET", playerSummaries.xml, true);
xhttp.send();
1: you need to check if browser supports XMLHttpRequest or ActiveXObject Object.
2: .open() and .send() should not be written inside onreadystatechange function.
3: check if your referencing your xml file correctly, playerSummaries.xml or playerSummariesXml.
You can see my below code on GIT hub , which uses plain JS ajax to support for html,css,json ,xml,image responses.
https://github.com/vijaysani/JavascriptAjaxWithDifferentResponses
let me know if your still facing any issues.

A partial build of jQuery just for $.ajax (XMLHttpRequest) functionality?

Is there a way to obtain or compile a stripped down version of jQuery, that just contains the $.ajax function, and anything that it depends on?
NOTE:
Background: Wish to create a script which includes just this function in-lined within my own (with proper attributions of course)
Including the entire jQuery would be overkill for my requirements
A great example of what I am looking for is Modernizr:
http://modernizr.com/download/
The download page allows you to select which parts you want, and it will work out the dependencies, and give your a partial build, containing just what you have asked for.
Why do you even need jQuery?
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
// Success! run your success function
resp = this.responseText;
} else {
// Error :( run your error function
}
}
};
request.send();
request = null;
Or a POST:
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
// Success! run your success function
resp = this.responseText;
} else {
// Error :( run your error function
}
}
};
request.send(data);
request = null;
Taken from here, a fantastic resource for Vanilla JS alternatives to jQuery. This should work with IE8+.

Categories