JQ DataTable setting Ajax call headers - datatables

I am using jq datatable, I want to send a token in JQ DataTable ajax request header.
Just like a regular ajax call like this
$.ajax({
url: url,
type: 'POST',
data: data, // data I want to post at server
contentType: 'application/json; charset=utf-8',
headers: {
'Token': Token //token I want to send in ajax header
},
cache: false,
async: async,
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});

you can add it in beforeSend, so your ajax would look something like this:
"ajax": {
"url" : 'changeToYourUrl',
"type" : 'POST/GET',
"beforeSend" : function(xhr) {
xhr.setRequestHeader('TOKEN',token);
}
hope this helps.

I found this usefull. JqDataTable how to add authorization header to ajax requests.

Related

How to handle the plain/text POST request in the cypress

I have a postman collection and It's POST call and the request body is type of plain/text and I just want to automate this using cy.request but I'm not sure how to pass the test body in the cy.request body section and it returned 400 bad request if I run the below code.
cy.request({
url: `${url}/user`,
method: "POST",
headers: {
'Content-Type': 'plain/text'
},
body: {
"confirmEmail": "true"
}
}).then(res =>{
cy.task('log',"Email id "+res.body.emailAddress);
return res.body;
});
}
The above request return .json response but the input request if text format and the same working fine in the postman tool.
Passing the request body in the below format in the postman tool and its working fine.
confirmEmail=true
My assumption is in the request body our endpoint is expecting a boolean value, but you are passing a string. So changing "confirmEmail": "true" to "confirmEmail": true should work.
cy.request({
url: `${url}/user`,
method: 'POST',
headers: {
'Content-Type': 'plain/text',
},
body: {
confirmEmail: true,
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})
In case you need to pass parameters in your URL you can directly use qs
cy.request({
url: `${url}/user`,
method: 'POST',
qs: {
confirmEmail: true,
},
headers: {
'Content-Type': 'plain/text',
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})

The request sent by jQuery or JavaScript doesn't contain the Header so I received error 405

I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers
Try this:
$.ajax({
url: "URL",
type: "GET",
‎headers: {
‎"Authorization": "Bearer HASHKEY"
‎},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.

How to call a method from API Controller using ajax

I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);

Amazon Gateway API with Lambda - Could not parse request body into json

I seem to be getting a issue with Amazon Gateway API not liking my sent params for example.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {
"device": "test",
"datetime": "1446757400919"
},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("DOES NOT WORK - <br>" + JSON.stringify(returnhtml));
}
});
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("<br>WORKS ???? - <br>" + JSON.stringify(returnhtml));
}
});
Here is a working example.
http://jsfiddle.net/Uwcuz/4315/
Can someone let me know why it wont let me send params every time i add a parameter i get this error.
{
Type = User;
message = "Could not parse request body into json.";
}
OK THIS WORKS BUT SEEMS A BIT WEIRD TO ME.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: "{\"device\": \"test\",\"datetime\": \"1446757444524\"}",
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("WORKS - <br>" + JSON.stringify(returnhtml));
}
});
The problem lies in how you send the data to API Gateway.
Without knowing the details of your API configuration I am guessing that you have a Request Mapping setup for application/json.
jQuery will by default post your data as application/x-www-form-urlencoded but you want to send it as json.
You can do this without having to fiddle too much with the data yourself:
var requestParams = {
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
method: "POST,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
"device": "test",
"datetime": "1446757400919"
});
};
var request = $.ajax(requestParams);
The key here is JSON.stringify() and telling jQuery that the dataType is json as well as setting the contentType to application/json.

sencha touch2 Login examples

I need a cross-domain user login request instance, please help me, thank you!!
My code
Ext.data.JsonP.request({
url: 'http://25.30.2.3:8080/newvbo/applyaction!longin',
params: {
username:'13881901678',
password:'111111',
},
success: function(response, opts) {
alert('1');
},
failure: function(response, opts) {
alert('2');
}
});
My question is, I not receive the server returns the value, I wrong?
You can Try this
Ext.Ajax.request({
method:'GET',
contentType:'application/json; charset=utf-8',
dataType:'json',
url:'http://........Login',
disableCaching: false,
withCredentials: true,
useDefaultXhrHeader: false,
callbackKey: 'callback',
params: {
EmailId:Ext.getCmp('usernametwoway').getValue(),
Password:Ext.getCmp('loginpasswordtwoway').getValue(),
},
success:function(response)
{
console.log(response);
var res = response.responseText;
var jsonarr = Ext.decode(response.responseText);
console.log(jsonarr);
var myres = jsonarr[0].Result;
console.log(myres);
switch(myres)
{
case '1':
console.log("Registration response is successfully");
Ext.Viewport.setActiveItem({xtype:'passengerdetailstwoway'});
break;
case '0':
console.log("Failed");
Ext.Msg.alert("Error","Login Failed",Ext.emptyFn);
break;
Based on the responce you can Specify the Switch case..
Hi #jesse you can try for cross-domain something like this,
Ext.Ajax.request({
url: 'your_url_path',
timeout: 90000,
params: {
withCredentials: true,
useDefaultXhrHeader: false,
username:'13881901678',
password:'111111',
},
success: function(response, o) {
if(response != '') {
alert('1')
}
},
failure: function(response, o) {
alert('2')
}
})
For cross-domain you need put withCredentials: true and useDefaultXhrHeader: false.
I hope help you.
I would like to suggest you a different approach because sending login credentials as GET parameter to remote server over http is not a good idea, instead you should use POST method over HTTPS. Now you would think JSONP doesn't support POST so how can I do this, but if you are going to install your app on Phone or iPad it would do remote call from browser without using JsonP, which means you can use normal AJAX proxy to do whatever you want. Check this out:
How to use json proxy to access remote services during development
Which means this should work:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'https://login_url',
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
},
failure : function(response) {
}
});