XMLHTTPRequest POST getting stuck - javascript

I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
However, this code gets stops after xhr.onload = function(). So I never get the response back. Is there an error in my code?

You forgot to send the request.
xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here");

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
xhr.send("data to be send");
Try this.

Related

How is the proper way to use the Cisco CompressedClientLog Finesse API?

How can I best format my POST request for the Cisco API CompressedClientLog? 
https://developer.cisco.com/docs/finesse/#!compressedclientlog%e2%80%94post-compressed-log-to-finesse/compressedclientlogpost-compressed-log-to-finesse
CompressedClientLog—Post Compressed Log to Finesse
var data = new FormData();
var logObj = '<ClientLog><logData>This is some logged data for the log file</logData></ClientLog>';
data.append("logData", logObj);
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log("Gadget is now engaged" + this.responseText);
}
});
xhr.open("POST", "https://finesse1.xyz.com/finesse/api/User/finadmin/CompressedClientLog");
xhr.send(data);
Response is:
<ApiErrors>
<ApiError>
<ErrorType>Parameter Missing</ErrorType>
<ErrorData>logData</ErrorData>
<ErrorMessage>Missing logData in the ClientLog object</ErrorMessage>
</ApiError>
</ApiErrors>
Where am I going wrong?

Getting "Unexpected end of JSON input at JSON.parse

Just getting a Syntax Error, "Unexpected end of JSON input at JSON.parse"
var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();
request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
request.send();
trivia = JSON.parse(request.responseText);
console.log(trivia);
The problem is that you need to wait for the response to arrive before continuing on. You can achieve just that using the AJAX request's onload event:
var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();
request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
request.onload = function() {
trivia = JSON.parse(request.responseText);
console.log(trivia);
}
request.send();

ajax fail to POST on API

i tried everything, and i still cant figure out whats the problem, i'm trying to 'POST' something on teachers server that we had for homework, and i have no idea what i'm doing wrong ,i'm stuck for like 2 hours already.
here is my code.
const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE){
console.log(xhr.response);
}
}
xhr.open('POST',url);
xhr.send(attendee);
Please see this snippet, you are getting The 401 Unauthorized error, you have to attach authorization token variable to the request.
xhr.setRequestHeader('Authorization', '~Token~');
There will be an other api that will get authorization token.
const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE){
console.log(xhr.response);
}
else{
console.log(xhr.status);
}
}
xhr.open('POST',url);
xhr.send(attendee);

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

How to pass base64encode string through XMLHttpRequest() post request

I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps

Categories