I've created a ClickListener which is supposed to make a POST request to my server. Most of the times, the POST request is made but sometimes, it fails to make a POST request no matter how many times I try. Can anyone help me understand what the issue is and how to resolve it? This is my code where I'm handling that:
$("#Button11").on("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/addtolist", true);
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded",
"Access-Control-Allow-Origin",
"*"
);
var parameter = "dc=deal1";
xhr.send(parameter);
window.location.href = "/final_page.ejs";
});
The issue
XMLHttpRequest.send() is an asynchronous method, that mean this method only ask the request to be sent but it will not be done instantly. Most of the time, this does not matters, but in your script, you redirect the user right after it, so, sometime, the user is redirected before the request is sent.
The solution
You have to wait the request to be done before redirecting the user, thankfully, XMLHttpRequest have a method to achieve it. It is the XMLHttpRequest.onload() method. So you can update your script to :
$("#Button11").on("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/addtolist", true);
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded",
"Access-Control-Allow-Origin",
"*"
);
var parameter = "dc=deal1";
xhr.send(parameter);
xhr.onload = function(){
window.location.href = "/final_page.ejs";
};
});
As mentioned in the comments, JQuery also have an integrated solution for making request, I recommend you reading it's documentation to have an even better solution.
Your location change is killing your Ajax before it finishes
Also why not use the much simpler $.post now you have it?
None of your headers are needed and the auth header is not even allowed to be set by you
$("#Button11").on("click", function() {
$.post("/addtolist",{"dc":"deal1"},function() {
window.location.href = "/final_page.ejs";
})
});
Related
I have started with the minehut API, and after looking at the docs (see a copy here) it uses get and post.
As a newbie to javascript etc I dont know how it works.
Part 1 - Get Info
for example: I want to get info about a server, it says to use GET https://api.minehut.com/server/{server-id}
How would i get for example playercount from it so that i can give that info to my code and display it on my website.
Required headers: is also mentioned in the docs, what are these and how do i use them?
Part 2 - send info
Now say for example i want to run a command, the docs say to use POST /server/{Server ID}/send_command. It also mentions Required headers saying it needs
Content-Type,
Authorization and
x-session-id
how would i send a string so that it would use POST to run a command
What you need to send or receive data using GET/POST methods is XMLHttpRequest object.
var server_id = "EXAMPLE_ID";
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(this.readyState == 4){
// Data sent back available in this.responseText
// For example:
var recData = this.responseText;
// further handling
}
}
req.open('GET', 'https://api.minehut.com/server/' + server_id, true);
req.send();
Or in case of POST request:
req.open('POST', 'https://api.minehut.com/server/' + server_id + '/send_command', true);
req.setRequestHeader("Content-Type", "pplication/x-www-form-urlencoded");
req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
req.setRequestHeader("HeaderNameExample", "ItsValueExample");
req.send('optionalVar=sentData&foo=bar&etc");
In some cases preflight request can be done (especially with custom request headers) and the request might fail. To avoid that you might try invoking the opening with user/password instead. For cross domain request Access-Controll request should be made which allows for cookies to be set.
req.open("GET", url, true, username, password);
req.open("POST", url, true, username, password);
req.withCredentials = true;
I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
First of all I have to say that I have NO EXPERIENCE in Ajax and I just need this one explanation in order for me to create a simple chrome extension.
There is not much I could find on internet even tho I believe this is very simple.
I need a part of code where I would "call" url from website and I need to adjust certain arguments in that url.
Request URL:http://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE
Request Method:POST
Request Payload :
{amount: 1, user_id: 12345678}
amount: 1
user_id: 12345678
(this is something I get from Network panel- with url and token changed to real things - while calling url automatically from website, but I need to be able to call it manually too.)
So I have an idea of mixing AJAX(which I don't know) and JS in order for me to call this url.
I would use variables for both TOKEN_VALUE and amount&user_id, but I don't know how to even call that url and how to set "request payload" in order for site to do the thing I want it to do.
I would really appreciate if someone would be kind enough to help :)
Work I have done, but doesn't work:
var request=new XMLHttpRequest;
request.open("POST","https://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE"),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),request.Payload("user_id=12345678&amount=5");
I basically tried to remake an example I found online, but it didn't work out, therefore I need someone to actually explain to me how this works and how can I adjust arguments that I need.
function callAjax() {
// the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
// #data contains the $_POST[amount],$_POST[user_id],$_POST[whatever] since we are using POST method, if you're using PHP as a server side language
var request = new XMLHttpRequest(),
url = 'place_here_the_url_only',
data = 'amount=1&user_id=12345678&whatever=dataYouWantToSendToServerFromBrowser',
token = document.querySelector('meta[name="csrf-token"]').content;
// when the server is done and it came back with the data you can handle it here
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do whatever you want!
console.log("The request and response was successful!");
}
};
// method post, your giving it the URL, true means asynchronous
request.open('POST', url, true);
// set the headers so that the server knows who is he talking to, I'm using laravel 5.5
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
// Token needed
request.setRequestHeader('X-CSRF-TOKEN', token);
// then you send the data and wait for the server to return the response
request.send(data);
}
Ajax: Asynchronous JavaScript And XML
It is a mean of communication between the browser and the server hosting the website, it cannot call any other server.
Asynchronous means the website continues to function normally, until the request is returned from the server and the:
if (this.readyState == 4 && this.status == 200) { }
gets triggered
I used ajax to send the data. I was successful in implementing it using two different approaches:
1) Using method 'POST' and sending data in send() method by setting requestheader.
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send("userName=xyz&password=abc");
2) Using method "POST" and appending parameter values in the URL as:
var xmlHttp = getXMLHttpRequest();
var url="login.do?userName=xyz&password=abc";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send();
Since this is an ajax call, URL will not be visible in the browser window, so I wanted to know which approach is better and why?
Thanks in advance
Here is W3 recommendation for you.
That pretty much says what exactly you need to do.
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead.
Though it is saying post, internal meaning of it is to keep the URL clean.
Apart from the given two ways, if I were you, I prefer clean codes (imagine 10 query param).
var data = new FormData();
data.append('userName', 'xyz');
data.append('password', 'abc');
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send(data);
Putting data into the URL's query parameters doesn't make it a GET request. A POST request is a POST request; the difference is between sending data in the URL or sending it as POST body. There's no fundamental difference between both in this case, the data is equally (non) visible for anyone who cares to look.
The only arguable difference in security is that the URL will likely be logged by the server and/or proxies, while body data usually isn't. But then again, you're already sending the data to the server you presumably trust, so even that doesn't make much of a difference. And the server(s) could be logging the body as well if they wanted to.
Semantically I'd send the data in the POST body, but that's not because of security.
I'm using the code below to do a POST request to an API and grab some data from the server
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/json; charset=UTF8");
request.setRequestHeader("X-Accept", "application/json");
request.send(JSON.stringify(data));
My issue is how to decide if I should do it asynchronous or synchronous. Well actually my issue with async is that I'm not sure how to apply an eventListener which would listen to the completion of that XHR.
If I use asynchronous calls my web application fetches the data too late and the application loads with the previously cache data, though If I use synchronous calls it takes about a second to fetch and display the data and I'm not sure how to display a "loading" icon since I'm not sure where to attach the eventListener.
Could someone make it clear on how to use XHR properly?
I'd like to mention that this is my first time trying to use XHR to fetch data from a server through an API.
Stick with asynchronous, as it doesn't freeze the browser and allows for a more elegant way of dealing with the response. As for the completion of the XHR, use this:
request.open("POST", url, true);
request.onreadystatechange = function () {
if (request.readyState === 4) {
// XHR state is DONE
if (request.status == 200) {
// HTTP 200 status code (success)
// HIDE YOUR "LOADING" SPINNER
// use request.responseText to get the response's content
}
}
};
request.setRequestHeader("Content-type", "application/json; charset=UTF8");
request.setRequestHeader("X-Accept", "application/json");
request.send(JSON.stringify(data));
// SHOW YOUR "LOADING" SPINNER
As always, it's a good idea to read some documentation on it: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest
"my web application fetches the data too late and the application loads with the previously cache data" - I'm not sure exactly what you mean by that, but if you explain more how your code above is being called/used, I'm sure it could be reorganized to work together properly.