Can I set a global header for all AJAX requests? - javascript

This doesn't seem to be working :
$.ajaxSetup({
headers: {
Accept: 'application/vvv.website+json;version=1 ',
Authorization: 'Token token=\"FuHCLyY46\"'
}
});
I would have thought it would. If I add these filters specifically to my AJAX call then they do work. I'd like to do this globally for all AJAX calls.

I did some additional tests and the code you posted works perfectly. If you have problems with something in how the parameters are setup, you could always to go the beforeSend call and modify the xml request yourself.
$.ajaxSetup({
beforeSend: function (xhr)
{
xhr.setRequestHeader("Accept","application/vvv.website+json;version=1");
xhr.setRequestHeader("Authorization","Token token=\"FuHCLyY46\"");
}
});

It's also possible to do this in a framework-agnostic way by monkey-patching the open method:
var o = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){
var res = o.apply(this, arguments);
var err = new Error();
this.setRequestHeader('X-Ajax-Stack', JSON.stringify(err.stack));
return res;
}
In this example I'm sending stack trace information via a header, which allows the backend to know where Ajax requests originated, even if it's from third-party code that doesn't use jQuery.
(Note: careful about headers getting too big)

The beforeSend answer does not establish the same header's as adding header directly to the ajax call. So in order for jQuery to do this properly I add this :
headers: myGlobalHeaders
where myGlobalHeaders is a global variable. Unfortunately, I have to write this extra line on every single ajax call. Terrible! Maybe I'll edit the jQuery framework to handle this..

Related

How to make POST request with javascript in a Chrome Extension?

I was wondering if there is anyway to make this:
<form action="http[://localhost/.../script.php" method="POST">
a regular call. I don't want it to run on form submit, but instead I wan't it to run when I call a function.
Would I use jQuery or AJAX?
You may use Fetch API on chrome to do so:
// building your form values
var data = new URLSearchParams();
data.set('var1', 'value 1');
data.set('var2', 'value 2');
// send to the endpoint
fetch("http://localhost/.../script.php", {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}).then(function(response) {
// check the response object for result
// ...
});
You can use ajax to call the the php function and store its response.
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
Make sure u include jquery CDN
You could use AJAX to post data to your PHP script, which will then run.
Note that jQuery and AJAX are not alternatives for each other.
AJAX is an asynchronous HTTP request (which is what you want).
jQuery is a javascript library which you can use to make AJAX calls.
I would take a look at https://api.jquery.com/jQuery.post/
This is a shorthand function for making an ajax POST request. E.g.:
function triggerMyPhpScript(data) {
$.post("http://localhost/.../script.php", data, function(responseData) {
// do something with the response of your script
});
}
I also like the Fetch answer from Koala Yeung. This will also work fine on modern browsers. Keep in mind that if you want to support ancient browsers (e.g. internet explorer), you need to implement feature detection and a fallback in case fetch is not supported by the browser.

Method of an ajax request

Is there any way to know what is the method (GET/POST/PUT/DELETE) of an ajax request in Javascript or Jquery?
I went through the docs but I couldn't get a solution. My aim is to set headers if the ajax request is not of GET method.
Instead of using jQuery for making AJAX calls, recommend using either native fetch or in case you need to support older browsers you can use https://github.com/github/fetch.
By default AJAX calls will be GET calls. If you want to use another HTTP method, then you need to set the method as an option. For example using native fetch
fetch('someURL', {
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(payload),
});
Another good read is https://davidwalsh.name/fetch.
This is while making the ajax call. If you want to what was the original call made from the response you get, unless the server explicitly sets the value in the header, I don't think you will be able to figure that out.
I was able to solve this.
$(document).ajaxSend(function(e, xhr, options) {
if(options.type != "GET") {
xhr.setRequestHeader(HEADER, VALUE);
}
});
options gives the type of the request that's being made.
Thank you everyone for help!

GET request 'Accept: */*' header is causing a 406. Is it possible to remove it?

I am trying to GET the binary data of a file from an API; I must make this request using JavaScript and I cannot modify the API in any way.
I am currently using the following approach;
function getUserFile() {
$.ajax({
type: 'GET',
url: userData.file.link,
beforeSend: function(request) {
request.setRequestHeader('Accept', 'application/octet-stream');
request.setRequestHeader('Authorization', 'Bearer ' + authToken);
},
contentType: 'application/json',
success: function(data) {
// Do something with data
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
}
When I trigger this request from inside the browser it fails and returns a 406. This is occurring because the browser (I believe?) is adding the */* value to my Accept header. It must only contain application/octet-stream for the API to accept the request.
Is it at all possible to remove this extra header value, or disable it from being added to the request in the first place?
EDIT:
Running both this and the real API call through JSFiddle does not append the */* value to the Accept header. Running the same code from a standard HTML document does add the value. What is different about these two that might be causing the value to be omitted on one while not the other?
EDIT:
The aspx page in question is running either JQuery 1.5.x or 1.8.x
While it's not the answer as to why this was/is occurring, I have found a working solution to the problem.
In place of the $.ajax() call, I can use a XMLHttpRequest.
var request;
request = new XMLHttpRequest();
request.addEventListener("load", getComplete);
request.open('GET', userData.file.link);
request.setRequestHeader('Content-type', 'application/json');
request.setRequestHeader('Accept', 'application/octet-stream');
request.setRequestHeader('Authorization', 'Bearer ' + authToken);
request.send();
The 'default' header value was only being appended to my ajax calls; specifically those made from only certain .aspx pages.
If I log the request from beforeSend: this default header value is already present. Somewhere in the project a setting or a piece of JS is causing the ajax calls to be initialise with the Accept header value of */*.
No $.ajaxSetup({ ... }); is present in the project, and using delete $.ajaxSettings.headers["Accept"]; makes no difference. My assumption is that the JQuery file being used by these pages contains modifications that affect ajaxSettings.
EDIT
I managed to track down the JQuery file being used by this portion of the asp.NET project. This JQuery file had been modified to include certain default when making AJAX calls. This is why the direct approach of using the XMLHttpRequest was successful.

How to get JSON Object from URL

I'm very new to web development.
When I input this link
https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412
into my browser, I can see the JSON object.
What do I need to do so can I use this JSON object in my javascript? I've tried using JQuery's $.getJSON with no luck.
EDIT
Using JSONP worked! Appending &jsonp=readJSON&?callback=? to the URL gave me back the JSON I wanted. Thank you for all the informative answers.
$.getJSON( "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412&jsonp=readJSON&?callback=?", function() {
console.log( "success" );
})
function readJSON(response){
console.log (response);
}
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
Your backend can proxy the request from this site
You have to use a JSONP object if it's supported by the API
I'm no clear about your question, but I think you can use a call ajax, something like:
$.ajax({
url: "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412",
type: 'get',
cache: false,
success: function (response) {
console.log(response);
}
});
This should get the concept across if you are using JQuery... but you can use just about anything.
var url = "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412";
var result;
var settings = {
success: function(data){
result = data;
//do anything else related to this data here as you need it fetched, and is not linear.
}
}
$.ajax(url, settings);
Now, I noticed you used getJSON, which is pretty much the exact same. I did not however see you use a success function, so if you did your way, have you tried:
$.getJSON(url, function(data){
result = data;
});
I may be mistaken, but you say: "With no luck" so i have a limited understanding as to what you tried with $.getJSON
Not directly from inside a web browser, no. You would need to use a proxy: another server that makes this request in your behalf and then gives you the result.
Why not?
Web browsers are pretty tight on security. One of the strategies for protecting users from malicious activity is restricting the domains your Javascript can make HTTP requests to.
An HTTP request from your domain (the origin) to another domain is called a cross-origin request. These are forbidden by default, and you won't be able to read the response body, unless the received HTTP response includes the header Access-Control-Allow-Origin.
How then?
By using a proxy as an intermediary. The proxy is not a web browser, it doesn't care about Access-Control-Allow-Origin, and will read the response anyway.
There are a number of proxies you can use. An easy one is YQL (the Yahoo Query Language). Here's an article on the topic, using jQuery: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax

Can Prototype or JQuery return an HTTP status code on an AJAX request

url = "http://example.com"
new Ajax.Request(url, {
onComplete: function(transport) {
alert(transport.status);
}
});
I'd like that to return a status of 200 if the site is working, or 500 if it is not working, etc.. But that code is returning 0 all the time.
Ultimately, I want to have a setinterval function that regularly pings a website for uptime status.
With JQuery you should get your status with a code similar to what you have, and it will be something like this:
$.ajax({
url: 'some.url.com',
type: 'POST',
complete: function(transport) {
if(transport.status == 200) {
alert('Success');
} else {
alert('Failed');
}
}
});
And if you want to use prototype your code should only add this:
onXYZ:function(transport){
}
In the text above XYZ should be replaced by the http status code you want to catch for the response.
Hope this helps
Ajax libraries don't "return status codes" themselves; that code is the HTTP response code returned in the response from the server. A status code of 200 indicates success; 404 indicates "not found", etc.
It's probable that a response code of 0 means the request wasn't even attempted. Is the request URL under the same domain (subdomain, if applicable) as that which the page is coming from? If not, then you may be running into problems with the same-origin policy, which prevents scripts from creating arbitrary requests.
To work around this, you'll need to proxy the data on the server side; for example using a script/framework handler/whatever which executes the web request and passes the data back down to clients. Call the "local" proxy instead of the remote data source.
Prototype has onXYZ callbacks, for example:
new Ajax.Request(url, {
method: 'get',
on500: function(transport) {
alert("failed!");
},
onSuccess: function(transport) {
alert("success!");
}
});
On thing though, if the website is down (as in, not reachable), it will not return a 500 error, so your approach isn't very good for starters.
I was able to make remote domains work by creating a server side proxy file to pass the status code through. I used the code on this post to create a asp.net page that would just set the status code of the page to the web request status code.
I then used the ajax example that Chermosillo provided like so.
$.ajax({
url: 'URLTestProxy.aspx?url=http://some.url.com',
type: 'POST',
complete: function(transport) {
if(transport.status == 200) {
alert('Success');
} else {
alert('Failed');
}
}
});
This way here you can get around the same origin policy and still get the status code of the remote url.
It may be helpful to know that the transport param in the example is an XMLHttpRequest object. Full details of the methods and properties available from this object can be found here:
http://www.w3.org/TR/XMLHttpRequest/#the-xmlhttprequest-interface
Most notable in the context of this question are the response items:
readonly attribute unsigned short status;
readonly attribute DOMString statusText;
DOMString getResponseHeader(DOMString header);
DOMString getAllResponseHeaders();
readonly attribute DOMString responseText;
readonly attribute Document responseXML;
You should be able to get any arbitrary header with the getResponseHeader() method.
For jQuery you might try:
complete: function(transport, textstatus){
alert(transport.getResponseHeader("Status"))
}
warning: not tested

Categories