When to use POST method when using AJAX explanation - javascript

I am learning about AJAX using W3school resources, and there is a phrase in this URL that I do not understand: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
It is about when POST should be used when using AJAX. It says:
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no
size limitations).
Sending user input (which can contain unknown
characters), POST is more robust and secure than GET.
What does, A cached file is not an option (update a file or database on the server). mean?

if a file is cached it is stored locally on the clients machine which means that the data is already present and there is no need to go get it from a server. The reason this isn't an option for the post (it is but not best practice) is because the posts job is to send data to the server with the intention of updating a record or a file (sometimes if it's a really small change to the configuration of the server you would store it in a .json or .config or .txt file. This could be a post to update that file) / or database record.
The post will hide the data being sent (kind of, you won't see it in the URL unlike a GET Request which will show the name=value pairs in the URL). Post request is meant to update a piece of data.
It's impossible to update the server data with the local cached data - because if you update the local file/data it's not updating on the server, which is accessed via RESTful CRUD (GET/GET:ID/POST/PUT/DELETE) (Create, Read, Update, Delete) patterns

Related

I'm trying to send a JSON object from client to server and receive a response but all the approaches I find are either inadequate or overkill

I'm in a situation where I'm not sure what is the correct way of doing this. I'm trying to take a large json file, send it to the server, process and reorder it, and then send it back to the client. I don't want to store any data in a database. I know there's the HTTP GET verb, but the amount of data I would be inputting would be longer than the max length URI. I also read that you shouldn't try to do this with a HTTP POST either.
I looked into WebSockets as well but to me it appears to be overkill. I would only need the socket for the time that it takes to do the computations, then I would close it. Also I want to share the data with only the client who sent it to me.
Does any one have recommendations as for what to do. Maybe just a push in the right direction with a few links I can read. I'm really looking for something that runs down the middle of these two methods.
Why don't you just use a HTTP POST request? Taken from an info box on
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
> Request has body Yes
> Successful response has body Yes
> Safe No
> Idempotent No
> Cacheable Only if freshness information is included
> Allowed in HTML forms Yes
As you see, a HTTP POST request is used for sending data to the server, and if the POST request was successful, the server sends data back to the client. Perfect for your situation, I think.
A POST request doesn't have to be used within a HTML form; you could use XHR, AJAX, the fetch API, or any other way you can find to send the server a POST request. And yes, you could send JSON data with it.
If you need more convincing:
When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Adding a new user through a signup modal;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Extending a database through an append operation.
Notice that there, it said that a POST request can be used to provide a block of data to a data-handling process.
Hope this helps you. :)

How to store a json Object serverside and respond with it

I am trying to make a webpage and server where a user can enter in recipes and have them sent to (using JSON) the server and have the server store them in a file so that if the server is closed and reopened the user can request for something they've entered previously and can get it. I know how to send the JSON object both to the server and how to send the JSON object back to the client. I should note this can't use jquery.
What I need help with is how to store it in a file server side and get the contents from it later using a node.js server. They should all be stored in the same directory and I need to know how to get a list of the recipes in that directory. I've tried looking around but I can't seem to find the answer :(.
Example:
user makes a recipies
{ name:"cheese n waffles"
time:90,
ingredients:"cheese, eggs and waffles",
equipment:stove
};
Browser sends the JSON object to the server.
Client asks for a list of the recipes stored.
user asks for the recipe for spaghetti.
what I need help with:
server gets a list of the recipes it has stored
server takes the JSON object and stores it in /serverRootDir/recepiesStorage
server accesses /serverRootDir/recepiesStorage and gets the spaghetti recipe
You should be using a JSON based database such as MondoDB
It takes some learming however implementing with a text file will eventually become much more work and will function poorly
(Posted on behalf of the OP).
I have solved the problem. I will be using:
To read a file (access a recipe): fs.readFileSync() or fs.readFile().
To save a file (update a recipe): fs.writeFileSync() or fs.writeFile().
To get an array of files in a directory (retrieve the list of recipes): fs.readdirSync() or fs.readdir().

How can you access the HTTP response from a server using client-side JavaScript?

I'm trying to do client-side processing of some data sent in a server's HTTP response.
Here's what I'm working with: I have a web application that sends commands to a backend simulation engine, which then sends back a bunch of data/results in the response body. I want to be able to access this response using JavaScript (note..not making a new response, but simply accessing the data already sent from the server).
Right now, I am able to do this via a kludgy hack of sorts:
var responseText = "{{response}}";
This is using Django's template system, where I have already pre-formatted the template context variable "response" to contain a pre-formatted string representation of a csv file (i.e., proper unicode separators, etc).
This results in a huge string being transmitted to the page. Right now, this supports my immediate goal of making this data available for download as a csv, but it doesn't really support more sophisticated tasks. Also, I'm not sure if it will scale well when my string is, say, 2 MB as opposed to less than 1 KB.
I'd like to have this response data stored more elegantly, perhaps as part of the DOM or maybe in a cache (?) [not familiar with this].
The ideal way to do this is to not load the csv on document load, either as a javascript variable or as part of the DOM. Why would you want to load a 2MB data every time to the user when his intention may not be to download the csv everytime?
I suggest creating a controller/action for downloading the csv and get it on click of the download button.

How can I process POST data sent from one HTML to another? [duplicate]

I want to pass some textbox value strictly using POST from one html page to another...
how can this be done without using any server side language like asp.net or php
can it be done using javascript??
thnx
You can't read POST data in any way on javascript so this is not doable.
Here you can find similar questions:
http://forums.devshed.com/javascript-development-115/read-post-data-in-javascript-1172.html
http://www.sitepoint.com/forums/showthread.php?454963-Getting-GET-or-POST-variables-using-JavaScript
This reading can also be interesting: http://en.wikipedia.org/wiki/POST_%28HTTP%29
This expecially suggests why this answer (wikipedia is the source):
GET
Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.
(This is also true of some other HTTP methods.)[1] The W3C has
published guidance principles on this distinction, saying, "Web
application design should be informed by the above principles, but
also by the relevant limitations."[10] See safe methods below.
POST
Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request.
This may result in the creation of a new resource or the updates of
existing resources or both.
POST data is added to the request. When you do a GET request the data is added to the url, and that's why you can access it through javascript (and that's why it's not parsed and you have to do it manually). Instead, POST send data directly into the http requests, which is not seen in any way by the html page (which is just a part of what is sent through the http request).
That said, only server side language will receive the full HTTP request, and definitely you can' access it by javascript.
I'm sorry but that is the real answer

request parameters ordering undefined [in multipart/form-data or in general] - what to do?

I am writing a web application that submits a form (one of its fields is mulitpart/form-data, so obviously POST must be used and not GET, since the files might be really big). One of the fields is kinda transaction/upload_id and the other is obviously the file contents. While uploading, a progress bar must be displayed.
The known fact says that the order of parameters is undefined in general, meaning that any of (file content / upload_id) might come first.
Is there any acceptable / recommended way to cause the browser to send the upload_id before sending the file content?
Is it a considered a correct implementation - to expect the upload_id to come first OR there is a better / most common / more correct way to handle the problem? In that case - it would be fantastic to hear some details.
Update: my server-side language is Java/Servlets 3.0
Well, the better answer (without utilizing filters) would be to publish the upload_id(s) as a part of the URL (after '?'), even when issuing a POST request. In that case, they will be always processed ahead of files' contents.
Using servlets as well, and in my case I wanted to run my CSRF filter in my servlet before I started streaming the file: if the filter failed, I can kill the request before I've uploaded my 20gb video file, as opposed to the default PHP implementation where the server only hits your script AFTER its parsed the entire request.
Its been a bit of a hack on my part, but in the couple of cases I've had to do this I've cheated and put the non-file request parameters into the URL and in every case (using pretty much every browser I've tested with) an Iterator over the request parameters on the server (I'm using commons fileupload in streaming mode) has received the non-file request parameters first before the file data was received. Somewhat fragile, but not unworkable.
I'm assuming that if you order your request parameters with the file <input> as the last item you'll get the same behavior.
You shouldn't have to worry about the order in which the parameters are sent. If so, then your server-side code is very brittle.
A multi-part request will contain the field name of every form field that is passed in. Use the name to reference that field regardless of the order it was sent in.
If you are parsing the post body by hand, I suggest you look at existing projects like Apache FileUpload which abstract that away.

Categories

Resources