Adding basic http authorization in a ajax json script - javascript

Not really sure how to add authentication in an ajax call for JSON information. I am trying to follow the examples given http://domainapi.com/documentation/how-to-use-domainapi/servuces-provided/domain-availability-api.html to check the availability of a domain name, however it keeps doing a http form pop up asking for username and password.
I thought I had everything right in my code:
function domainAvailabilityCheck(domain) {
$.ajax({
type: 'GET',
url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
beforeSend: setHeader,
success: function(spitback) {
console.log(spitback.content.domainList.status);
},
dataType:'jsonp'
});
}
var setHeader = function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}
Not sure what it is that I am doing wrong.

Your beforeSend isn't allowing Jquery to pass in the xhr object for the header modifications. The line should be
beforeSend: function(xhr) { xhr.setRequest(......); } // all-in-one, no extra function needed
or
beforeSend: function(xhr) { setHeader(xhr); } // call your separate function

you may also:
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}
function domainAvailabilityCheck(domain) {
$.ajax({
type: 'GET',
url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
beforeSend: setHeader,
success: function(spitback) {
console.log(spitback.content.domainList.status);
},
dataType:'jsonp'
});
}
actually it doesn't matter where to put the variable setHeader which holds the anonymous function, but this way up it's more readable (for me and my soft-compiler ... ;)

Related

Ajax callback to check variables as global

I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!

How to handle X-CSRF-Token for jQuery POST in UI5?

I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.

How to parse parameters from Ajax return string

I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});

What do I have to write to make a SinonJS fakeServer call success with special parameter

I am doing this ajax call:
$.ajax(this.apipath + "/login/refreshToken/", {
type: "POST",
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Token ' + localStorage.getItem("loginToken"));
},
dataType: "json",
success: function (response) {
alert("success");
self.set('authenticated', true);
self.set('user', JSON.stringify(response.user));
self.set('loginToken', response.loginToken);
localStorage.setItem("loginToken", response.loginToken);
window.$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Token ' + response.loginToken);
}
});
}
});
Now I want to use Jasmine to write a test. I use SinonJS to create a fake server. I want to test, if the success function is called and if the loginToken item was set. Therefore I use this instruction:
server.respondWith(session.apipath + "/login/refreshToken/", [200, { 'Content-Type': 'application/json' }, JSON.stringify([{user:"asdf",loginToken:true}])]);
success is called but the response object does not contain a loginToken attribute. How can I make the server give the correct response object to the success function?

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Categories