Ajax setRequestHeader is not working - javascript

I am trying to add header to ajax request.
I use setRequestHeader but it do nothing. I can look in firefox that request headers doesnot contains Authentication! What i am doing wrong?
And how to add header?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://test/test.svc/news",
dataType: "json",
beforeSend : function(xhr) {
xhr.setRequestHeader("Authentication", "Basic " + Base64.encode(username + ":" + password))
},
success: function(data) {
alert('Success');
},
error: function() {
alert("Loading data error...");
}
});
}

Try username and password instead
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://test/test.svc/news",
dataType: "json",
username: 'username', /* not user */
password: 'pass',
success: function(data) {
alert('Success');
},
error: function() {
alert("Loading data error...");
}
});
}
username -
A username to be used in response to an HTTP access authentication request

Related

how can I authenticate to a rest web service by ajax

I want to send username and password to a Rest web service to recover the Token. I tested this code but always sends me to error function
$.ajax({
type: "POST",
url: "http://192.168.1.89:1111/connect/token",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', btoa(username, password));
},
success: function() {
alert('Thanks for your comment!');
},
error: function(xhr, status, error) {
alert(error);
}
});

How to display responded page by server using GET request in ajax call

function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
});
}
This is my ajax GET request I want to display the given url in html.
The below is the whole snippet with my login logic.
$(document).ready(()=>{
$('#login').submit((e)=>{
$.ajax({
type: 'POST',
url:'http://localhost:3000/login/users',
data: {
email: $('#email').val(),
password: $('#password').val()
},
success: function(data, status, req){
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
var token = localStorage.getItem('t');
regCall(token);
// window.location.href = '/';
},
error: function (req, status, error) {
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
alert('Invalid email and password');
window.location.href = '/login';
}
});
e.preventDefault();
});
})
This is the whole code of snippet.
extract response data from SUCCESS function:
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(data){
//targetElement should be replaced by the ID of target element
$("#targetElement").html(data);
}
});
}
By using the success callback function you can display the response content on the HTML place
**First method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(responseData){
$("#div or class Id").html(responseData);
}
});
}
**Second method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
}).done(function(responseData){
$("#div or class Id").html(responseData);
});
}
**NOTE:**
Make sure you are having the jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to simplfy the passing of parameter

I have these method in c# which requires 3 parameters
public void Delete_AgentTools(int ID,int UAM,int mode)
{
some code etc.
}
and I use javascript ajax to call this method and pass the parameter
function Delete_AgentTools(toolAccess, toolId, UAM) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: "{'toolAccess':'" + toolAccess + "', 'toolId':'" + toolId + "', 'UAM':'" + UAM + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
}
you see for me I want to simpilfy on how I pass the parameter in javascript. Is it possible to pass it as an object to the c# or simplify the passing of parameters in javascript
You can convert a js object as a JSON using JSON.stringify
var data = {};
data.toolAccess = value1;
data.toolId = value2;
data.UAM = value3;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
function Delete_AgentTools(toolAccess, toolId, UAM) {
var data = {};
data.mode = toolAccess;
data.ID = toolId;
data.UAM = UAM;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
No need to change in your C# code.

POST 400 error, ajax request

Why cant I save this, I get 400 (Bad Request),
and on headers response i get The CSRF token could not be verified.
$(document).ready(function() {
$("a#copylink").click(function (e) {
e.preventDefault();
var data = $('#campaign-form').serialize();
$.ajax(
{
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
data: data,
success: function(data){
alert(data);
}
}
)
});
});
on backend:
public function actionCampaignSave()
{
var_dump($_POST);
}
You can pass the [headers] parameter in your ajax call like this.
$.ajax({
url : 'campaignsave',
method : 'POST',,
headers : {
'X-CSRF-TOKEN' : $('input[name="token"]').val()
}
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
}
});
Just make sure you've place {!! csrf_field() !!} on your [view] blade template to append the $(input[name="token"); html tag to get the token value to get the CSRF token as well. Hope this helps
Pass csrf token using headers property on ajax
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
headers: { 'X-CSRF-TOKEN': 'token' }
data: data,
success: function(data){
alert(data);
}
});
Try this it may help you
$.ajax({
type: "POST",
url: 'campaignsave',
data: {test : data},
success: function(data) {
alert(data);
}
});

I can't get Basic Authentication to Pass

I have searched the forums here for a while and am still at a loss. I am doing Basic Authentication with a predefined username and password.
I know that the username and password are correct because I can directly log in.
I have tried passing a "header", "username", "password" and as you see below using "beforeSend".
$.ajax({
type: "GET",
url: "https://vcc-na10.8x8.com/api/stats/groups.xml",
datatype: "xml",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password)); },
error: function (){
alert('cant connect');
},
success: function (){
alert('connected');
}
});
I think you need to use the headers parameter to pass authentication. Try this:
$.ajax({
type: "GET",
url: "https://vcc-na10.8x8.com/api/stats/groups.xml",
datatype: "xml",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
error: function() {
alert('cant connect');
},
success: function() {
alert('connected');
}
});
Try sending the username and password directly in the ajax config.
$.ajax({
type: "GET",
username: username,
password: password,
...

Categories

Resources