I've been digging for an answer to the above solution, but I did not found something interesting.
Can you guys please explain it in clear words??
Ajax is a generic term that means "Making an HTTP request and processing its response, from JavaScript, without leaving the page".
JSONP is a specific means of making an Ajax request that is performed by adding a <script> element that loads an external JavaScript program that does nothing except call a specified function with some data as the first argument. It is a hack to get around the Same Origin Policy. (It is obsolete in the face of CORS which provides a much safer, and more refined, means to do the same thing).
Related
I am developing a REST API for one of my projects.
I need to use GET requests. I don't seem to understand why using url query strings is superior to body.
There are some obvious differences between the two ways to request data - like being able to see the parameters in the url, or the fact that the requests can be saved in the brower's history.
But is there anything more to it?
Is it bad to request data with body?
There's nothing wrong with using a body. GET method does not have a body not because of some prejudice against the usage of body.
If you have a look at the HTTP protocol specification, you might have some insight:
"The GET method means retrieve whatever information (in the form of an
entity) is identified by the Request-URI."
In simpler words, GET method is created to retrieve some resource using only URI. In even simpler words - if you can get some resource using only URI - GET is a method you should use.
As a matter of fact, you can send body with GET request, but it will just be ignored (more information here: HTTP GET with request body)
If you need to pass a body for whatever reason you will need to use a different method. POST is a prominent example:
"The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line."
If you working on REST API's I would highly encourage to read HTTP specification https://www.rfc-editor.org/rfc/rfc2616
Is it bad to request data with body?
Yes, it is bad.
The problem is that, in HTTP, GET method is specifically defined to not to include a request body.
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request. -- RFC 7231
What's going on here, largely, is that early versions of the HTTP specification had some ambiguities about the handling of message-bodies in requests. In effect, putting a message-body into a GET request was "undefined behavior".
The working group is strongly motivated to ensure that the standard remains backwards compatible.
Part of the point of REST is that we are all using a common standard, so that the general purpose tools (browsers, caches, reverse proxies, spiders...) work for everybody -- or more specifically for everybody that abides by the standard.
With regards to GET, including a message body doesn't make sense when you consider caching semantics. Caching semantics in HTTP are currently defined by RFC 7134, the high level summary is that the target-uri is the primary cache key; caches only need to understand the metadata in the HTTP request to do their job properly.
If we were to apply semantics to the body of a GET request, we'd also need to define, in a general way, how those semantics affect cache behavior.
For instance, if you imagine a query scenario (like GraphQL), the expected representations in the response depend on the information encoded into the request body. So now you need to start defining when two request bodies are "the same" - is white space significant? does the content encoding matter? what about if the body is zipped? and so on....
We don't have this kind of problem with unsafe requests (for example, POST), because standards compliant caches MUST write through requests that are unsafe. There's no need to explore the representation of the message-body of the request because there are no circumstances where the contents would change this requirement.
There have been attempts at creating a new standard for the HTTP method that is safe and includes a message body. It's probably doable; in the sense that we introduce a new method token, and declare the semantics to be safe (so that we can perform preemptive fetching, and repeat requests on an unreliable network) and perhaps that public caches cannot store the responses, but must instead forward each request to the origin server.
That said, people have been aware of the gap for a while, and the problem doesn't yet have a standardized solution - so there may be some difficult aspect to it that isn't obvious (in addition to the political problems of adoption vs inertia).
What is the best method for going about differentiating AJAX requests and other browser HTTP requests? I'm using vanilla NodeJS with AtomicJS as the AJAX library. It does not seem to set the 'X-Requested-With' header, which I read was used by JQuery to indicate AJAX requests. Should I switch to a library that does? Is there another way to detect AJAX requests? Should I just attempt to set the header manually, and are there any potential issues involved in doing so?
There is no reliable way to tell the difference (short of you explicitly setting a header or other indicator on all of your own requests). More importantly, it should not really matter how the request was sent.
You could explicitly state that the request was coming from an Ajax request in the header or in the body of the request, but likely the better way to do this would be to have a separate endpoint on the server for an ajax request.
For instance your uri for an non ajax request might be
http://myserver.com/non-ajax-uri
and then you could have another endpoint at
http://myserver.com/ajax-uri
If most of the behavior is shared between the two endpoints simply encapsulate it in another function that both of the end points share.
I'm making ajax request to server on another domain but I don't actially need its response, just to know that it got my request.
When everything is ok, in Chrome Developer Tools (Header status) it says «canceled» and console writes «XMLHttpRequest cannot load» but server gets my requests.
When server is down then header status is not a number but just «failed».
Trying to catch this critical difference on JS I get XHR status 0 in both cases.
I'm making ajax request to server on another domain
You can't make an ajax request to a different domain, due to same-origin policy. You want to look at JSONP, which essentially writes out a <script> tag for a remote URL.
What is JSONP all about?
Detecting success/error with JSONP calls is tricky, it doesn't work like typical ajax calls at all. Ideally you want the remote server to call a callback function on your page, as the above link describes.
If you don't control the other domain, you can attempt to detect errors by using a timeout. Here is a post discussing the jQuery timeout argument for this, though you could certainly implement your own timeout with raw javascript as well.
(extremely ignorant question, I freely admit)
I have a simple web page with a button and a label. When I click the button, I want to make a REST call to an entirely different domain (cross-domain, I know that much) and display the results (HTML) in the label.
With other APIs, I've played around with using JSON/P and adding a element on the fly, but this particular API doesn't support JSON so I'm not sure how to go about successfully getting through.
The code I have is:
function getESVData() {
$.get('http://www.esvapi.org/v2/rest/passageQuery?key=IP&passage=John+1', function (data) {
$('#bibleText').html(data);
app.showNotification("Note:", "Load performed.");
});
}
I get an "Access denied." Is there anyway to make this call successfully without JSON?
First off, JSON and JSONP are not the same. JSON is a way of representing information, and JSONP is a hack around the same-origin policy. JSONP works by requesting information from another domain, and that domain returns a script which calls a function (with the name you provided) with the information. You are indeed executing a script on your site that another domain gave to you, so you should trust this other domain.
Now when trying to make cross domain requests you basically have 3 options:
Use JSONP. This has limitations, including the fact that it only works for GET requests, and the server you are sending the request to has to support it.
Make a Cross Origin Resource Sharing (CORS) request. This also must be supported by the server you are sending the request to.
Set up a proxy on your own server. In this situation you set an endpoint on your site that simply relays requests. ie you request the information from your server, your server gets it from the other server and returns it to you.
For your situation, it the other server doesn't have support for other options, it seems like you will have to go with options 3.
I have a working prototype of a BHO (simple C# with COM interop) which injects JavaScript to any page which is loaded by IE. Simple scripts are working like console.log(..) etc.
My goal is to make AJAX requests from the injected javascript to localhost. I understand it's an X domain request, but can't figure out how to implement it.
I carefully read about XMLHttpRequest and XDomainRequest (both gives me Access Denied)
Btw I would like to send/receive JSON and XDomainRequest allows only plain/text (why?, surely not security issue enabling plain/text but not allowing json...) Also I've read XDomainRequest does not allow localhost.
I understand that response header should allow X domain with 'Access-Control-Allow-Origin: *' (Is this the response of the page I am injecting into?)
Maybe I can modify/patch the response header to allow X domain from my BHO? Is this possible?
As a last resort I considered make the request in my C# BHO. However this means to call from javascript to C# (maybe it's working) but the main problem that this call is a synchronous call. Even if I issue the request in async way in C# in it completion handler then I must call back a javascript completion handler. This sounds as terrible overenginering calling from javascript to C# then calling back from C# to javascript not talking about the robustness and perfomance loss.
Any ideas?
Thx in advance