Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm wondering, why are we still using GET method in AJAX requests for example:
$.ajax({
type: "GET",
url: "SomeController/GetSomething",
data: { id: 100}
});
GET is handy, when you want to store data in url, when you are querying Google and you want to send that query to friend or whatever else. On the other hand, we have security gaps. They are not big (I'd say they are obstacles), but it'd be slightly better to use POST when you don't want to show form data. Moreover, POST can store any type of data, control data size and hide somehow passing variables.
Is it a good solution to always use GET in places, which are not "public" (search bars, article page, user profile, ...) and use POST everywhere else? With this approach, all AJAX queries should be send using POST method.
When using POST XHR, you use a two-step process : sending the headers first and then the data, but you use Ajax for responsiveness, right ? So why use a two-step process when you can use a one-step process (GET XHR)?
Furthermore, AFAIK, GET request are cacheable, POST are not.
Last but not least, as some have pointed : HTTP verbs do have a meaning.
Keep on using GET XHR for getting datafrom server, and POST XHR for sending data.
Like you said, GET is not secure but it allows us to copy and paste links and get the same results. POST is more secure in the way it does not show the parameters directly, it still needs work on the backend to plug all the holes.
The key is not to forget why one is called "GET" and the other one "POST".
GET is accessible, so not good for anything sensitive, but easy to manipulate directly.
POST should be used to submit to the server side, sensitive or "lengthy" data.
This is only my opinion:
A savvy user who really wants to know what data is being posted will always be able to discover exactly what data is being transmitted during an http request. The only tool that you really need for this are the tools that are built into modern browsers. If you transmit using HTTPS, then a third party will be able to discern GET parameters, but not POST data, so I would say you are correct that sensitive data should only be sent as POST. Otherwise, as a security tool, POST over GET serves a similar function to a password mask on password inputs (prevent someone from looking at your data over your shoulder).
Now, to your question "Is GET better...?"
I would say that just like with synchronous http requests, you should use GET when the user or your application need to get data, and POST when your app of the user needs to post data (for persistence - in the session (like a login), or a database, etc). So it's really more of a semantic difference. Practically, you could use post for everything if you wanted to.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently working on a school project and I need some help. I ran into a problem when trying to put the data I read from another IP address (using AJAX) into a MySQL database. I tried using node.js but because I'm calling the function when I press the button on a webpage it doesn't work... So any suggestions or tips on how to make node.js work.
ajax function:
function AddShoots() {
$.ajax({
method: "POST",
dataType: "json",
url: "http://192.168.1.8",
success: function (html) {
for ($i = 0; $i < html.length; $i++) {
console.log(html[$i]);
}
},
});
}
The data I get and would like to insert into database:
EDIT: additional explanation
sorry for the HTML/CSS there was an error while copying. To clarify my endpoint I have a python image recognition program written on raspberry PI, the Raspberry PI server that is on the IP returns the numbers seen in the picture, I would like to insert the numbers into a MySQL database and I need help with how to do that because I only inserted data into tables with PHP before, but I can't do this in this case because I'm using AJAX (at least not with my knowledge) I hope this explains everything better.
Another edit:
A picture that might help with understanding (I'm super bad at explaining sorry English is not my primary language that's why I have bad expressions and a hard time explaining some stuff).
Sounds like you're getting your technologies mixed up a bit.
Lets clarify a few terms first:
NodeJS
Is a JavaScript runtime for server-side or backend code.
Runtime
An environment for code to execute like NodeJS or a web browser.
Server-Side
This refers to code running on a server. Could be PHP, Java, Python etc... or even JavaScript if you're using Node.
Backend
Usually means the same thing as "server-side" when people say "backend".
Frontend
In this context, "frontend" is referring to code being executed in a web browser.
AJAX
A style of HTTP request that a browser can use to send and fetch data without reloading the current page.
Now that we have that out of the way...
Node is a server-side runtime for JavaScript, so your JS code running in the browser has no way to talk to your Node code directly.
If you want to click a button in the browser and see data get written to your database you have to make an AJAX call to a url that your backend is listening to (known as an endpoint or a route).
It's a bit difficult to interpret your intentions from your example but I think you mean to send a POST to http://192.168.1.8. So you'll need a route configured in your Node app that can handle the AJAX request, and from there you can write the data to your database.
Of course you'll also need to pass the data with the request. That gets passed along with the options parameter in your $.ajax(/* ... */) call.
At a high level this is what I believe you're trying to achieve:
So basically your app should have at least two files:
index.html This will have your button as well as the JS code that fetches data from your Pi. This "front-end" JS will also have to send an AJAX request to your Node app.
app.js This will be your Node app. It will have to expose an endpoint that your front-end code can send data to. Inside the function of that endpoint, you'll handle writing the data to your database.
There's a library called Express that will help you make your endpoint. I recommend following their Getting Started guide: https://expressjs.com/en/starter/installing.html
Update
I see you updated your answer with a diagram. I assumed your mental model was probably exactly like that, which is why you're having a hard time.
When a user visits a url such as https://stackoverflow.com for example, the request doesn't go to the web browser. The request has to go through a server first. When you use Node, your app essentially is the server, and is responsible for returning the correct response.
In your case the response would be an HTML file like index.html for example.
That index.html is the webpage and it is going to contain your "front-end" JavaScript code, which can communicate to your Raspberry Pi server over HTTP to get that image data you're talking about.
JavaScript running in the browser has no way to communicate to a SQL database directly. So you have to send a request over the network to your Node service. Inside your backend application you can write the data to a MySQL database with the help of packages you can get from NPM. Here's an example of one: https://www.npmjs.com/package/mysql
Update 2
It sounds like you're more comfortable using PHP. You can swap NodeJS out with PHP and my diagram would still represent what you want to achieve at a high level. The key difference is you won't have to figure out how to set up a "route".
With PHP you can just have a file named something like SaveMyData.php:
<?php
// Get the body of the POST request
$data = file_get_contents('php://input');
// Decode the JSON string so you can work with it in PHP
$decodedData = json_decode($data);
// $decodedData is now an array of the data you sent from the browser
foreach($decodedData as $row) {
// write the row to your database here
}
Then the "endpoint" (making some assumptions about how your serving your app) is just http://localhost:8080/SaveMyData.php and that becomes the URL you pass to your AJAX call from the browser.
Your AJAX request would look something like:
function AddShoots() {
$.ajax({
method: "POST", // the post to your Pi I'm assuming?
dataType: "json",
url: "http://192.168.1.8",
success: function (data) {
$.ajax({
method: "POST", // this is going out to your PHP backend
dataType: "json",
url: "http://localhost:8080/SaveMyData.php",
data: data,
success: function (response) {
// do stuff with the response if you'd like
})
});
},
});
}
Tons of "best practices" are being violated here, but for the purposes of a school assignment this should get you pointed in the right direction.
This question already has answers here:
When do you use POST and when do you use GET?
(27 answers)
Closed 6 years ago.
We can accomplish the same thing by doing:
localhost:3000/endpoint?var1=val1&var2=val2
That we can do by using POST with a JSON body.
So why should anyone use PUT/POST/PATCH if they can get the same goals by using url params? Even with auth, instead of header, you can send the information of the auth token back and forth by using a parameter?
one reason is that GET parameters have to be URL-encoded.
then there are limitations of URL length documented in RFC I think.
This will make it difficult when transfering large data (e.g. file uploads,...)
additionally, developers may want to hide some informations from the user, to prevent users to bookmark a page with all these parameters...
Definitely NO reason for POST args is security on the transport layer. in both cases the data are plain text in HTTP, and both (also the URL) are encoded end-to-end when using a secure HTTPS connection.
It is more secure, because your data is encrypted and sent in the header of the request.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have the following XMLHttpRequest:
# ....
var request = new XMLHttpRequest();
request.open('GET', 'controllers/get_date.php', true);
request.setRequestHeader('Cache-Control', 'no-cache');
request.setRequestHeader('fn', 'get_date');
request.setRequestHeader('day', '27/11' );
# ....
And get_date.php looks like this:
if($_SERVER['HTTP_FN'] == 'get_date'):
$day = Common::sanitize($_SERVER['HTTP_DAY']);
$data = new MyFunction($day);
echo $data->my_data();
endif;
Basically I'm trying to get some data from $data->my_data() and all of this is working fine. However as my back-end skills are quite limited. I am wondering if this is a proper way (considering mainly security) or if I should take another approach.
You should avoid passing parameter data through HTTP header. HTTP header is for the HTTP layer to proper transport its data. It has its own purpose, but not for application parameters. Proxy, firewalls, gateways, load balancers etc could all inspect and re-write the header for the purpose of the HTTP transport. Your custom 'parameters' might get re-written, removed, or run into the same namspace of other header.
Instead, I recommend you to pass using query string using GET or POST data.
For example:
request.open('GET', 'controllers/get_date.php?fn=get_date&day=27%2F11', true);
And in PHP, getting the parameters using:
$fn = $_REQUEST['fn'];
$day = $_REQUEST['day'];
if($fn == 'get_date') {
...
Yes it's up to you!
First of all compliments for using the native XMLHttpRequest, which is supported by all browsers including the mobile ones. Using the jQuery's ajax is just performance loss.
Security
When talking about javascript there is no security. Zero.
I answered a question about How can I obfuscate(protect) JavaScript? some time ago... and there is really nothing you can hide as soon as you put it online. The only thing you can do is to annoying the "hacker". Also just using the native XMLHttpRequest increases the chance that all those jQuery fans don't understandd what you do! ;)
In the above post i used headers to validate the referrer...
Performance
XMLHttpRequest It's native... so it is the fastest approach..
All other libs include many userfriendly checks that simplify everything. Many checks means performance loss.
As you may want to use ajax for more than just one action i suggest you look at the function i wrote some time ago.
How do I return the response from an asynchronous call?
function ajax(a,b,e,d,c){ // Url,callback,method,formdata or {key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
I use it for various REST API's. Mostly you don't need to set the header and other stuff.
You could modify it and add the support for adding header information.
I see a very bad thing in your code.
request.open('GET', 'controllers/get_date.php', true);
True???
Don't do that. that should be never used. Not even with static files. Ajax is meant to be async! You will crash the users browser if the response of the php file is not fast enough. By crash i mean the browser is stuck nothing moves until the ajax content is loaded. So if it takes 5seconds to load the file, for 5 seconds you can't do nothing. the mouse/touch events don't work also every animated elements will be frozen.gifs/videos/cssstyles.
How to send the params
Slightly more security... short params, best performance ?? yep, use the headers the headers are send before anything else. But in reality i think not much changes as the final binary data is probably the same size as if you would send it over GET & POST.
GET or POST?
If at the end the gained security of sending the headers is not enough so you want to do it the "normal" way, then there is only one important thing to consider: how much data you need to send. I prefer post.. it allows to send more data. I use FormData to do so.
var fd=new FormData(form);// this is the whole form including upload files.
ajax(url,callback,'post',fd);
Something that does not seem very obvious is JSON.
I see nowhere JSON mentioned. Ajax withoutJSON is useless. js & php without json is useless. you can't just send strings... so
php
//php array to jsonstring
json_encode($array);
//jsonstring to php array
json_decode($string);
js
//jsonstring to js array
JSON.parse(string);
//js array to jsonstring
JSON.stringify(array);
In both cases (if the server nginx,apache,lighthttp is setup correctly) you don't need to worry about encoding. JSON is automatically encoded in utf8.
PHP
Some ppl would probably suggest to comrpress the php(ajax can handle zipped files) or even add the correct mimetype.
//header('Content-Type: application/json'); // not needed
echo json_encode($data);
but in both cases it takes more time. so don't.
keep the php file as simple as possible. as it's the one that take more time.
don't send elements , style or other html relative stuff. you should do that clients side. to keep the server agile.
mysql to json
https://stackoverflow.com/a/20948686/2450730
Now, looking at the comments, you use NODEJS :).
Use webSockets. use it for everything.
Forget about ajax, and do everything with websockets!!!!! Bidirectional communication. And you send only the data needed. No requests, no headers... no slow stuff.
Support
Both ajax and websockets , but also server sent events are not supported by older browsers.
If that is a problem don't use those technologies. Also using jQuery to allow ajax on ie6 is just a joke....
Btw now ff, ie, opera, android, safari, ios even a 4-5 year old version of those browsers support ajax,websockets & SSE
webSockets
I really like php, mysql nginx apache... but nodejs, websockets & json ..
Thats fun pure.
simple js example.
var ws=new WebSocket('ws://YOURIP:YOURPORT');
ws.onopen=function(){ //those events are also aviable with sse
ws.send('WS open!');//sending data to the server
// server handles each user individually very easely.
};
ws.onclose=function(){
console.log('WS closed!');
};*/
ws.onmessage=function(e){
//USE JSON
var Everythingyouneed=JSON.parse(e.data);
};
# nodejs side....
https://github.com/websockets/ws
look at the broadcast or send the data to eah user individually.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I often use AJAX to write into MYSQL database like so
$.ajax({
url: "writescript.php",
type: "POST",
data: { data : mydata,//this could be anything
},
success: function (html) {
//do something
}
});
And the writescript.php looks like this
$data=$_POST["data"];
//and then write into database.
Now this works and everything but then anybody can view the ajax request since it's pure JS and can be viewed from the page source. Given the information about the script name and parameters, an attacker could try to call the writescript as well and write into my database or read depending on what the script does. This is obviously not good. So am I missing something here? Is AJAX not designed to be used for such stuff? Or am I using it wrong?
I don't think a CSRF problem is presented here. CSRF means an attacker tricking a legitimate and authenticated user into hitting a page by clicking a link or any other means, in turns doing things on behalf of them. If your application checks for the header to make sure the request is an ajax call from the browser, and do not allow cross domain ajax requests, theoretically an attacker could not perform a CSRF attack
The problem you presented is more of an authorization problem. You are afraid that an attacker can write/read into your database, but any legitimate users should be able to do that, so naturally the solution is to add an authentication layer to fend off attackers.
You are missing "sessions". You can use sessions or any other authentication method to avoid this case. That is, be sure that the user is logged in at the beginning of the php code.
When user requests the page, generate a security token on that page and note it on the server. Then the response comes back, just compare the recieved security token with the saved one.
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
Through several threads I can see that the use of the MVC antiforgery token is overkill on areas of a site where a user is not authenticated.
I have an application that posts some information to mysite.com from site1, site2, site3, etc. Each site has a unique identifier that gets sent in the POST request through an asynchronous Javascript POST. The Javascript that is executed on site1-3, is generated on mysite.com, then returned to the sites with some Javascript variables populated.
So the lifecycle is as follows:
A page on site1 has a Javascript reference to mysite.com.
That link reference is to a controller route that generates Javascript to return to site1.
The end of the JS that is returned contains a POST request that goes back to mysite.com containing Url, browser, etc., details for the visitor of the page on site1.
I can read in the POST parameters just fine in the accepting controller from the JS POST request, however, what I wanted to know is if there is any point in adding an antiforgery token to the parameter list.
If so, I would have to generate it on the initial request, and pass it back as a JS variable in the JS returned to site1, then pass it back along with the form POST in the second request.
Since any processing on mysite.com will only occur if a valid account is found, is there any point in going through this?
If so, how would I generate the antiforgery token on at the controller level?
I would say that it depends on the sensitivity of the data that is being posted. If another user could cause harm (or annoyance) by crafting forged requests and submitting them, then I would say that it would be appropriate. It sounds like you're just collecting some usage information so that's not likely to be the case.
A one-time, random nonce might be a better solution. That would make it difficult to forge a request and prevent erroneous multiple submits, say from the user using a cached copy. Generate a random value (a GUID might work) on mysite.com, inserting it in the database and marking it as unused. Send it back with the POST. Check whether it has been used or not. If not used, then mark it used and perform your logging action. If it has been used already, discard the request as a duplicate submission.
Note that you wouldn't need a POST for this, a simple GET with URL parameters would be sufficient since the nonce will prevent it from being accidentally repeated.