How to set request header to the ajax object for jqGrid - ajax

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='
}
});

Related

Remove some cookie from ajax call with Axios

I use Axios in browser to call ajax request. Now I have a problem with some cookie that has high priority than some header. Per request I send a header as AUTHTOKEN but in cookie SESSIONID key stored that high priority than AUTHTOKEN header. In some scenario, I need to ignore cookie. This is my code:
axios({
url:`${sdpBasicUrl}/api/v3/requests/27363`,
method: 'get',
headers: {
'Content-Type': 'application/json'
'AUTHTOKEN': 'GHG23847923HGJ'
}
})
.then(res => {
console.log(res.data);
});
and this is cookie sample:
_z_identity=true; PORTALID=1; csrfcookie=aasdasdjh24234b2bjh4hjl; SESSIONID=ffd68d32a14841c99905e3cf4897e15ec9b4777020854a76821fd7e1eab6db2dcab482eb4cfea2ce7f5a6c47c80271d09f608ed985004e5c85681b2939681b18
What should I do? Do you have any solution to solve my problem?
You are able to pass in cookies through the header like this:
Axios.request({
url: "http://example.com",
method: "get",
headers:{
Cookie: "cookie1=value; cookie2=value; cookie3=value;"
}
}).then...
So if you don't want the value to be there, you could override the values.
https://github.com/axios/axios/issues/943
You can use transformRequest to modify the header for some requests. transformRequest allows changes to the request data and header before it is sent to the server. This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'.
transformRequest: [function (data, headers) {
// Modify the header here and return the header
return data;
}],
You can get more information about it on https://axios-http.com/docs/req_config

How to add header to request in Jquery 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

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

Vue.js-resource: http request with api key (Asana)

I'm trying to extract some projects from the Asana api with vue-resource (https://github.com/vuejs/vue-resource), a Vue.js add-on that makes ajax calls simple. I'm using an api key to access Asana, but I can't figure out how to pass the key in the request header using vue-resource.
In jQuery this works, using beforeSend:
$.ajax ({
type: "GET",
url: "https://app.asana.com/api/1.0/projects?opt_fields=name,notes",
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + "XXXXXX");
},
success: function (data){
// console.log(data);
}
});
Where XXXXXX is the Asana api key + ':' converted with btoa(). https://asana.com/developers/documentation/getting-started/authentication
Without needing to authenticate, the Vue instance should be fine with a simple request in the ready function:
new Vue({
el: '#asana_projects',
data: {
projects : []
},
ready: function() {
this.$http.get('https://app.asana.com/api/1.0/projects?opt_fields=name,notes', function (projects) {
this.$set('projects', projects); // $set sets a property even if it's not declared
});
},
methods: {
// functions here
}
});
This, of course, returns a 401 (Unauthorized), since there is no api key in there.
On the vue-resource github page there is also a beforeSend option for the request, but even though it is described right there I can't seem to figure out the correct syntax for it.
I have tried
this.$http.get( ... ).beforeSend( ... );
// -> "beforeSend is not a function", and
this.$http.get(URL, {beforeSend: function (req, opt) { ... }, function(projects) { //set... });
// -> runs the function but req and opt are undefined (of course)
I realize I'm being less than clever as I fail to understand a syntax that is right there in the documentation, but any and all help would be much appreciated!
Any takers?
Perhaps I'm missing some subtlety but can't you use the options parameter to the $get call to specify the header? From the docs: https://github.com/vuejs/vue-resource#methods
Methods
Vue.http.get(url, [data], [success], [options])
[...]
Options
[...]
headers - Object - Headers object to be sent as HTTP request headers
[...]
So for instance:
this.$http.get(
'https://app.asana.com/api/1.0/projects?opt_fields=name,notes',
function (projects) {
this.$set('projects', projects); // $set sets a property even if it's not declared
},
{
headers: {
"Authorization": "Basic " + "XXXXXX"
}
}
);
You can also configure the auth token for all calls like this:
Vue.http.options.root = '/root';
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
See the docs

Posting JSON using JQuery and to set HTTP content type - 'application /json'

I am using jquery to post Json data to server. However when I make a post request as below,
$.ajax({
type : 'POST' ,
url : uri,
data : jsonStrJson,
contentType : 'application/json',
success : successFunction
});
The http request header content type is not "application/json" even though I posting a json object.
Since it is not applcation/json, the server does not process the requset and returns 415.
Is there a way to set the header using javascript or jquery API?
Can you try this,
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: uri,
data: jsonStrJson,
dataType: "json",
success: function(json){
console.log(json);
}
});
"contentType" instead "contentTYpe" should also solve the problem. ;)
Also for setting http request header parameters you can try this approach:
$.ajax({
type : 'POST' ,
url : uri,
data : jsonStrJson,
headers : { 'Content-Type': 'application/json' }, //this line
success : successFunction
});

Resources