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.
Related
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 think I ran into a problem of the same variable being used, I might have gotten lucky in some cases where they were separated by function scope. I recently replaced all of my jQuery code with plain JS and this broke a few things however the gained speed/lack of dependency(extra file to download) was good for me in this situation.
So I have the basic form of:
var http = new XMLHttpRequest(),
url = "php/my-script.php",
params = encodeURI('some-param='+value);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(data) {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var result = JSON.parse(http.responseText);
if (result['status'] === "success") {
someFunction(result['some_key']);
}
}
}
http.send(params);
When I ran into the problem of the same http variable being used, I started to replace new ones with http1, http2, etc... seems like a bad idea. Especially having to replace all the http-method(?) calls afterwards like http2.responseText, etc... Should I make this into a function... then pass in the values to post and return the data out?
I guess I don't understand what happens when you call:
var http = new XMLHttpRequest();
Is that a one time use case, where after it has been called you need a new one for another post?
I will try the single-global-function approach. Everywhere I needed to do an AJAX call whether get or post, I always just used $.post/$.get on the spot, not sure if that's bad.
I'm currently sending POST requests to a PHP file of mine via a button with the following function:
function buttonFunction() {
$.post("http://ipaddress/core/file.php",{username:username, password:pword, coins:coins}, function(data) {
// Stuff
});
}
However, I recently found out that if the file process/PHP script is still running (trying to obtain the resulting data/response), and the user refreshes the page, the PHP process would still be running on the server. Also, if the user then decided to click the button again (after refreshing), there would be TWO PHP proccesses running from the same user on the server (that is, if the first one was still running):
Javascript Abort POST Request on Retry/Refresh (HIGH CPU Usage)
However, I came across sending POST data with XMLHttpRequest with Javascript:
Send POST data using XMLHttpRequest
So let's say I send my POST request this way, would it be safe to say when the user refreshes/closes out of the page, the PHP execution ends?
function buttonFunction() {
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
However, if this also does not work, how can I fix this issue (multiple scripts running in the background from the same user)? Whether that fix be in the PHP file or in the JavaScript itself, any help would be appreciated.
Edit 1:
Possible Solution?
What if I use XMLHttpRequest and abort the request before the page unloads?
window.onbeforeunload = function(event) {
http.abort();
};
I am quite new in this area.
I need to find out how to make a request to my solr server using Ajax
How can I give a url(my solr server's url) in request
Any body know how to deal with this?
How can i make a request to the below mentioned url
http://mysite:8080/solr/select/?q=%2A%3A%2A&version=2.2&start=0&rows=100&indent=on
See here: Corrected the Code Snippet as below
function getProductIds() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) console.dir(xmlhttp);
else alert('no response');
var ajaxURL = "http://localhost:8080/solr/select/?q=*:*&version=2.2&start=0&rows=100&indent=on";
xmlhttp.open("GET", ajaxURL, true);
xmlhttp.send();
}
This is my code, it always showing "no response"
Thanks.
You will have to prepare the URL before sending in the request first get the URl using javascript and then encode it to ajax format like below
var URL = location.href;
var ajaxURL = encodeURIComponent(URL);
xmlhttp.open("GET",ajaxURL,true);
after reading your question clearly it seemed it is a static URL hence you can do below
var URL = "http://localhost:8080/blah blah blah";
xmlhttp.open("GET",URL,true);
Are you sure it is Get request. because get requests are most of the time cached. also log the response object into Firebug console and inspect the object to know more. Since you get no response that means the server did not send you anything for the request you made.
I'm just now working on XMLHttpRequests to solr as well and I was stuck with what seems like an identical problem. I too am quite new at this. However, the problem for me was that of same origin policy. Firefox seems to give very little feedback when this problem occurs. Chrome at least give you a error message (most of the time?).
In Chrome you can get around this, but only for development purposes, by starting it with the '--disable-web-security' command line option.
I'm yet to find a good workaround for this problem for Solr. In general you avoid the restriction by only using requests with relative paths, but that doesn't seem possible when doing a request to another port.
Ways to circumvent the policy (I haven't had time to study this too much yet)
$.ajax({
url: "url path",
context: document.body
}).done(function(data) {
alert(data);
});
This one also will work.