Method of an ajax request - javascript

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!

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.

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

$.ajaxPrefilter() Vs $.ajaxSetup() - jQuery Ajax

While learning through ajax in jQuery, I came across 2 terms, viz., $.ajaxPrefilter() and $.ajaxSetup(). All I can find out is that these make some changes in AJAX before loading or making call to $.ajax().
Can someone simplify and explain these terms in easiest form along with a slight comparison of the two?
$.ajaxSetup() - Set default values for future Ajax requests. You could, for example, set the ajax URL that you always want to use for every request here.
Example:
$.ajaxSetup({
// Always use this URL for every request
url: "http://example.com/ajax.php"
});
$.ajaxPrefilter() - Modify existing options before each request is sent. You could, for example, append a query string component to every ajax request that is sent out.
Example:
$.ajaxPrefilter( function(options) {
// Always add "?debug=1" to every URL
options.url += (options.url.indexOf("?") < 0 ? : "?" : "&") + "debug=1";
});
$.ajaxSetup simply takes an options object, and uses it as the defaults for future $.ajax() calls (and other calls that are shortcuts for this, like $.get). For instance,
$.ajaxSetup( { dataType: 'json' });
makes this the default dataType for future calls.
$.ajaxPrefilter lets you run a custom function before sending each AJAX request to the server. It can examine the options to that call, and then change them in any way that it wants. So it provides much more flexibility and control than $.ajaxSetup.

Can I set a global header for all AJAX requests?

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..

jquery or javascript classic to add http header infomation in the browser (permanent value)

I was wondering if it is possible to add http header information on a browser using jquery or a classic javascript in such a way that this added info will always available during http request like the "user-agent" sent in the server?
sorry on my wild imagination... ;)
Best regards,
- toni
Since jQuery 1.5, there is a 'headers' option in the jQuery.ajax() method :
Try it this way :
$.ajax({
headers: {
'X-My-Custom-Header':'value';
},
// ... Your other parameters in order
// to define your request (url, method, etc.) ...
});

Categories