I'm not very familiar with APIs in general, but don't let that discourage you from answering this question ;)
I'm trying to pull data using the XMLHTTPRequest object. I was originally going to use a WSDL file, but the API I'm using does not have one. For some reason, when I'm trying to get the response displayed in an HTML file, nothing comes across, not even the error that it didn't connect. The api also requires the use of POST.
Here's the javascript:
window.onload = function startCall() {
var http = new XMLHttpRequest();
var url = "https://api.domain.com";
var params = "Version=2.00&ApiKey=111111111111111111&CallID=001";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", "226");
http.setRequestHeader("Host", "api.domain.com");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
function sendToHtml(url, 'target') {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('target').innerHTML = req.responseText;
}
}
else {
document.getElementById('target').innerHTML=" Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
And here's the HTML
<html>
<head>
<script type="text/javascript" src="call.js"></script>
</head>
<body>
<span onload="startCall" id="target">
</span>
</body>
</html>
Thankyou for any help
POST requests between domains are restricted so browser will not allow it.
There is option to enable it (CORS) by sending correct Access-Control-Allow-Origin, but it have to be done on API server.
Related
Is it possible to make a POSt request from a static website hosted on S3? Are there any workarounds?
Totally possible, just use XMLHttpRequest or add some lib (jquery) to help you with that:
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
</script>
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
I'm very new to JavaScript and have been looking for a solution for a while with no success. I'm trying to use the Last.fm API to retrieve the currently playing track on my account. This is what I have so far:
<html>
<body>
<p>this is an experiment!</p>
<script type="text/javascript">
const request = new XMLHttpRequest();
request.open('GET', 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user='+[MY_USERNAME]+'&api_key='+[MY_API_KEY]+'&format=json');
request.send();
request.onload = () => {
if (request.status === 200) {
console.log("Success");
var song = JSON.parse(request.response).recenttracks.track[0].name;
console.log(song);
}
};
request.onerror = () => {
console.log("error")
};
</script>
</body>
</html>
and I get an error in the console when I open the file in my browser. Any help is appreciated :)
Update: everything worked when I gave it the direct URL, e.g. I took out the +s and put the API key directly in.
I checked your code with the test-account and it works fine. So probably you get the empty result, let's add some checks:
request.onload = () => {
if (request.status === 200) {
// look at the response
console.log(request.response);
const recenttracks = JSON.parse(request.response).recenttracks;
if (!recenttracks.track || !recenttracks.track.length) {
console.log('track is empty');
return;
}
const song = recenttracks.track[0].name;
console.log(song);
}
};
It looks like you should use onreadystatechange to catch the response instead of onload.
Example:
request.onreadystatechange = function() {
if (this.status == 200) {
console.log(this.responseText);
}
};
You can read more about XMLHttp Requests here:
https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
I am using request along with cheerio to try to grab the link to a song on genius.com. The URL should be a YouTube link. The problem is that I simply cannot get the 'a' element to return its href attribute. This is my code (cheerio and request are loaded farther up in the script).
request('https://genius.com/Eminem-the-monster-lyrics' , function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var url = $('a' , 'div.song_media_controls-provider-icon').attr('href');
}
console.log(url);
});
I apologize if its a stupid problem or a stupid post. I'm still learning with all of this. Thank you to anyone for help.
// jQuery cross domain ajax
$.get("https://genius.com/Eminem-the-monster-lyrics").done(function (data) {
console.log(data);
});
// using XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://genius.com/Eminem-the-monster-lyrics", true);
xhttp.send();
<!DOCTYPE html>
<html lang="en">
<head>
<title>NK Chaudhary</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="demo">Add here genius.com</div>
</body>
</html>
I'm making a simple POST XMLHttpRequest, it is successfully posting the data but also the paylod getting appended to the URL. Is there anyway the data doesnt appended to the URL
var payLoad= JSON.stringify(ItemJSON);
var xmlhttp = new XMLHttpRequest();
xmlhttp.addEventListener("readystatechange", function () {
if (xmlhttp.readyState < 4){
}
else if (xmlhttp.readyState === 4) {
if (xmlhttp.status == 200 && xmlhttp.status < 300){
console.log("Success",xmlhttp.responseText);
}
}else{
alert("Error!! \\n There was an error while saving. Please retry again later.");
}
});
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(payLoad);
}
Response :
https://sample.com/api/apipipelines?apiName=asdasdaaaaaa&orgUnit=ASA&apiProductName=asdasd&leadDeveloperName=Sandeep&leadDeveloperEmail=sa11as1%40sandsssy.com&baseUrl=%2Fapplication%2Foip%2Fv1%2Fcase-management%2F&projectOwnerName=alisa&projectOwnerEmail=sa%40sasssssndy.com
It is because the header that you used while posting the content:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Change it to
xmlhttp.setRequestHeader("Content-Type", "application/json");
Reference for you: What is the difference between form-data, x-www-form-urlencoded and raw in the Postman Chrome application?
I would like to read the substatus code of the exception like 500.1 on the client side. How to achieve this?
here is my code on the server side:
if(string.IsNullOrEmpty(userEmail)) {
Response.StatusCode = 500;
Response.SubStatusCode = 1;
Response.StatusDescription = "Email fehlt";
return;
}
Client side:
if (xhr.status == 500 && thrownError.indexOf("Email") > -1) {
alert('Email is missing...');
}
else {
alert('Error...');
}
On client side you can use the getAllResponseHeaders() method of XMLHttpRequest.
If a correct http header is really sent, it will read it.
Example:
var request = new XMLHttpRequest();
request.open("GET", "ajax.php", true);
request.send();
request.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(this.getAllResponseHeaders());
}
}
Output is separated by "\r\n".
If somehow the substatus cannot go through, maybe you can use another http header field for your goal, even if it is not according to the standards...