How to add header to request in Jquery Ajax? - ajax

I'm trying to add header to request in Ajax with JQuery.
Below is the code :-
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",
data: JSON.stringify(patientDTO),
//crossDomain : true,
dataType: 'json',
headers: {"X-AUTH-TOKEN" : tokken},
success: function(patientDTO) {
console.log("SUCCESS: ", patientDTO);
/* location.href = "fieldagentHRA.html";*/
if (typeof(Storage) !== "undefined") {
localStorage.setItem("patUrn", patientDTO.data);
location.href="fieldagentHRA.html";
}
},
error: function(e) {
console.log("ERROR: ", e);
display(e);
},
done: function(e) {
enableRegisterButton(true);
}
});
I inspected this with chrome and found that header's body is not being added.
Then I used Requestly (Requestly is chrome+firefox plugin with which we can manually add a header to the request).
After manually adding header :-
In both the pics request header x-auth-token is present in "ACCESS-CONTROL-REQUEST-HEADERS" but "X-AUTH-TOKEN" header along with header value is present in second pic which is not there in the first pic.
So my question is how to add request headers in Ajax with JQuery ?

There are couple of solutions depending on what you want to do
If want to add a custom header (or set of headers) to an individual request then just add the headers property and this will help you to send your request with headers.
// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
If want to add a default header (or set of headers) to every request then use $.ajaxSetup(): this will help you to add headers.
//Setup headers here and than call ajax
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
// Sends your ajax
$.ajax({ url: 'foo/bar' });
add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():
//Hook your headers here and set it with before send function.
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your ajax
$.ajax({ url: 'foo/bar' });
Reference Link : AjaxSetup
Reference Link : AjaxHeaders

Related

Rendering Django template with Ajax call by calling endpoint

I am using ModelViewSet to fetch objects from my database and rendering them in a Django template. Since JWT Authentication is needed, I am sending the token in the header of AJAX request. I get the response back but if I redirect to the correct page I get a 401 Unauthorised.
$.ajaxSetup({
headers: {
'Authorization': "Bearer " + window.sessionStorage.getItem("token")
}
});
$(document).ready(function () {
$("#id").on('click', function (event) {
event.preventDefault()
var url = "myurl"
$.ajax({
url: url,
type: 'GET',
dataType: "html",
tokenFlag: true,
success: function(res) {
location.href = url
}
});
});
});
I want the page to redirect and the template rendered. It works fine in Insomnia.

How i can send delete request for to delete video in AJAX, its returning 204 status

I'm trying to delete my vimeo video by using AJAX request but its always returning 204 status code, and video is not deleting from account. Here is code example.
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: "post",
url: "https://api.vimeo.com/me/videos",
headers: {
"Authorization": "bearer xxxxxxxxxxxxxxx"
},
data: {
url: "https://api.vimeo.com/me"+videoID,
method: "DELETE"
},
dataType: "json"
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
Can anyone please suggest some changes required for this?
Thanks in advance
You are sending
a HTTP POST
to the URL https://api.vimeo.com/me/videos
with the Bearer token as a header
Note that it should be Bearer <token> (uppercase B), not bearer <token>.
with a data packet that contains another URL and HTTP method.
But according to the Vimeo API docs to Delete a Video, the request should be
DELETE https://api.vimeo.com/videos/{video_id}
with a note:
This method requires a token with the "delete" scope.
A jQuery ajax request should look something like this if the bearer token is correct:
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: 'DELETE',
url: 'https://api.vimeo.com/videos/' + videoID,
headers: {
"Authorization": "Bearer xxxxxxxxxxxxxxx"
},
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
You should be able to test this request using https://www.getpostman.com/ to verify the request and bearer token works outside of your CF app.

Can't set Access-Control-Allow-Origin request header

I making an AJAX request to the food2fork api and can't get by the No 'Access-Control-Allow-Origin' header is present error. I've tried setting the header in beforeSend and setting crossDomain: true but it didn't work.
This is my AJAX call:
$.ajax({
type: "GET",
dataType: 'json',
url: url,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data){
console.log('in ajax json call');
console.log(data);
$('#info').html(JSON.stringify(data));
}
});
I tried setting the request header server side in node express.js with:
router.get('/test', cors(), function(req,res)
{
res.set("Access-Control-Allow-Origin", "*"); //set header here
res.render('exampleSearch', {title: 'FM | Test'});
});
Cors is an npm package that sets cross-reference permissions but didn't help me solve the problem.
Can you tell me what I'm doing wrong?
Client-side request doesn't work in this case. I had to do the request server side:
router.post('/test', function(req,res){
var callback = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved
response.on('end', function () {
var recipes = JSON.parse(str);
//do something with recipes
});
}
var options = {
host: "food2fork.com",
path: "/api/search?key=[myKey]&q=" + ingredients
};
http.request(options,callback).end();
});
Used code from nodejitsu.com

Http Post request in Angular JS

We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter

How to set request header to the ajax object for jqGrid

I have the need to set the 'Authorization' request header to the httpXMLRequest. On the grid definition I have tried to set via ajaxGridOptions like the following:
ajaxGridOptions: { Authorization: 'Basic YWRtaW5AZGVmYXVsdC5jb206YWRTwa6=' }
and use the beforeSend event like the following:
beforeSend: function(jqXHR, settings) {
jqXHR.setRequestHeader("Authorization", 'Basic YWRtaW5AZGVmYXVsdC5jb206YWRTwa6=');
}
None of above works for me. What's the right syntax?
Thanks!!
You can use for example loadBeforeSend event handler of the jqGrid defined as the following:
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", 'Basic YWRtaW5AZGVmYXVsdC5jb206YWRTwa6=');
}
Another option as of today is setting the header globally for all AJAX requests:
$.ajaxSetup({
headers : {
'Authorization' : 'Basic YWRtaW5AZGVmYXVsdC5jb206YWRTwa6='
}
});

Resources