I have such part of code:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://someurl.com", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
doSomeTask();
}
}
}
xhr.send('login=mylogin&password=mypassword');
How can I know if my login&password are correct? In both cases xhr.status is 200.
Invalid Login/Password attempts are not HTTP failures. Only HTTP Failures return you 4xx or 5xx return codes. You might want to use the xhr.responseText or xhr.responseXML from the response to see what your backend is returning and base your decision according to that. Please refer to http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#dfn-responsetext for how the responses are obtained.
Also, there are tons of good Javascript framework that hide the complexity of making Ajax calls. JQuery makes the job of calling AJAX scripts extremely easy. You might want to investigate on that instead of writing raw XHR code.
Related
I am not able to make a post-call using xmlhttprequest in javascript. First, I am getting a 401 response code from server-side. Below is code I am using below code.
function makeRestCall(){
console.log("Rest call made")
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "myurk", false, 'username', 'password');
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send()
alert(xhttp.status);
alert(xhttp.responseText)
I am also getting
"Request has been blocked by CORS policy"
I am able to do a rest call from postman and using basic auth and getting response also
I have referred various links for making a rest call using javascript.
Link 1 Link 2
But still, I am not able to resolve the error. Can anyone tell what is wrong am I doing.
I've spent hours messing around with this... and I don't understand why I'm getting an undefined response when I use Javascript to make a request. My flask app is extremely basic and looks like the following:
#app.route('/timespent', methods=['GET', 'POST'])
def calculateAvgReadTime():
return jsonify({'result':'Success'})
The Javascript code I'm using to make a request to this endpoint is the following:
var xhr = new XMLHttpRequest();
// Setup our listener to process compeleted requests
xhr.onreadystatechange = function () {
console.log(xhr.status)
// Only run if the request is complete
if (xhr.readyState !== 4) return;
// Process our return data
if (xhr.status >= 200 && xhr.status < 300) {
// What do when the request is successful
console.log(JSON.parse(xhr.responseText));
}
};
xhr.open('GET', 'https://xxxxx.herokuapp.com/timespent');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
What's confusing is the following:
if I use Python or software like Insomnia, then the request is returned as expected and nothing is wrong - this is what makes me think something is wrong with the Javascript...
When I change the URL in the Javascript to "https://jsonplaceholder.typicode.com/todos/1", it works as expected and returns a json - this is what makes me think that my flask app is wrong...
Some help would be greatly appreciated.
I'm using HTML macros in confluence to automate some tasks in Jira. I tried the following REST call in the code below to add a comment to a ticket and I get the error: 400: Bad Request. The request sent by the client was syntactically incorrect.
I can't see any issues with my JSON or code. This pretty much fails for other operations I've tried such as creating/updating tickets.
xmlhttp = new XMLHttpRequest();
var url = "http://<CONFLUENCEURL>.com:8090/plugins/servlet/applinks/proxy?appId=<APPID>&path=http://<JIRAURL>:8080/rest/api/2/issue/TEST-3/comment";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}else{
console.log(xmlhttp.responseText);
}
}
var parameters = {
"body" : "Hello world!"
};
function addComment() {
xmlhttp.send(JSON.stringify(parameters));
}
I eventually created an identically ordered JSON object, turns out that the parser the server side uses does not follow the JSON specification in that it expects the correct order.
As in, the fix would be to follow the JSON specification server side, or replicate identically the structures being sent to the server.
function load_binary_resource(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) {
document.write("fail downloading loader");
stop = 1
};
return req.responseText;
}
filestream = load_binary_resource("exec")
what is this doing and what would responseText contain?
I am not sure which part of the code is causing confusion. Some elaboration would be helpful. However, here is a bit more detailed understanding of what this function is doing:
This function is sending an HTTP Request to a server that is reachable by traversing a path specified by the url parameter. req.open sets the method of your request to GET. It seems that you are sending no data with the request (as seen by req.send(null)). Finally, if the status of the request is anything other than 200 (which indicates that the request was OK), then this piece of code indicates a failure. You know the type of req.responseText to be of type text/plain since the line req.overrideMimeType('text\/plain; charset=x-user-defined') is included. Here is a resource to learn about XMLHttpRequest and the overrideMimeType function enter link description here
How can to request url or website address and show response code with javascript or jquery?
i.e
request www.google.com
if (response_code = 200) {
print "website alive"
} else if (response_code = 204) {
print "not found";
}
I'm assuming from the jquery tag that you mean to do this in a browser, not from a server running NodeJS or similar (although there is a NodeJS module for jQuery).
Although you can request URLs and see the response code using the XMLHttpRequest object, the Same Origin Policy will prevent your accessing virtually any sites other than the one the page itself was loaded from. But if you're pinging the server your page was loaded from to make sure it's still there, you can do that:
function ping(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("get", url);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) { // Request is complete
callback(xhr.status); // Tell the callback what the status code is
}
}
}