Calling sync ready made async ajax javascript function - javascript

I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.

For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.

Related

User Defined Exception is not working in JavaScript Promise

I implement user-defined exception in javascript code but it is not catching the exception.
I am providing my code :
function sendRequest(URL, Data, authorization, requestType,cuboidName) {
var Response = new $.Deferred();
var json;
if (requestType.toString() == "GET") {
$.ajax({
url: URL,
type: "GET",
dataType: "json",
headers: {
'Authorization': authorization,
'Accept': 'application/json'
},
success: function (result) {
Response.resolve(result);
//console.log("Response : " + JSON.stringify(result) + "\n\n\n");
},
error: function(err){
throw new Error("Error Code:\t"+err.status+"\nReason:\tCuboid Download failed for Cuboid:"+cuboidName);
}
});
}
return Response.promise();
}
I am calling the sendRequest function from the following code :
async loadDatatypeCuboid(dataCuboid)
{
try
{
dataTypeCuboiId = "444";
var res3 = new $.Deferred();
Utils.sendRequest(this.baseUrl+"rest/v1/grid/"+dataTypeCuboiId+"?importTid=-1&view=LATEST&mode=0&baselineId=-1", null, Globals.authorization, "GET","Datatype").then(function (result) {
res3.resolve(result);
if (result.status == 500) {
return;
}
else{
}
});
return res3.promise();
}
catch (error)
{
console.log(error);
}
}
I am not able to catch the thrown error. The console is showing as :
Utils.js:26 Uncaught Error: Error Code: 500 Reason: Cuboid Download
failed for Cuboid:Datatype
can anyone suggest How to Handle Exceptions in JavaScript Promise?
Thanks in Advance

Make another ajax call to get headers before each actual ajax call - jquery

I have to make an async call which uses cookie to get bearer token which has to be passed to make actual ajax call for the resource.
And I have written the following code which works awesome and get's me the result.
Can I use ajaxPrefilter or beforeSend options to get the tokens, I tried to find documentation for ajaxPrefilter which says it accepts a function, but does that waits for that function to be finished before making actual call?
Token retrieval function
function getTokenUsingCookieAsync() {
return new Promise(function (resolve, reject) {
$.ajax('/retrieve-token').done(function (result) {
resolve(result.token);
}).fail(function (message) {
reject(message);
});
});
}
Actual execute function:
function execute(url, method, data) {
var deferred = $.Deferred();
getTokenUsingCookieAsync().then(function (response) {
var reqSettings = {
async: true,
url: url,
cache: false,
type: method,
headers: {
Authorization: 'Bearer '+ response,
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data ? JSON.stringify(data) : null
};
$.ajax(reqSettings).done(function (result) {
deferred.resolve(result);
}).fail(function (message) {
deferred.reject(message);
});
}).catch(function (message) {
deferred.reject(message);
});
return deferred.promise();
}
So the following pseudo code is possible or not?
$.ajaxPrefilter((options) => {
$.ajax('/retrieve-token').done((result) => {
options.headers = {
Authorization: `Bearer ${result}`
};
});
});
$.ajax('actual-url')
.done(whatever);

How can I prevent getting a dialog popup window to login with basic authentication?

Currently we are trying to access the reed.co.uk api and get the json results of jobs from an account. I have managed to access the API in chrome and get the results but in Safari (Version 10.0.1 (12602.2.14.0.7)) and Firefox(v 50.1.0) I get the dialog pop up that asks me to log in.
I have tried multiple versions of Ajax to get this working but nothing seems to fix the issue at all. Here is what I have got:
var clientId = "c*****-***-****-****-*********0";
var clientSecret = "";
var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
$.ajax({
type: 'GET',
url: 'http://www.reed.co.uk/api/1.0/search?employerId=488552',
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
crossDomain: true,
headers: {
'Authorization': 'Basic ' + authorizationBasic
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
},
statusCode: {
401: function () {
result = false;
},
200: function (response) {
result = response;
}
},
async: false,
success: function (result) {
var token = result;
console.log(token);
},
//complete: function (jqXHR, textStatus) {
//},
error: function (req, status, error) {
alert(error);
}
});
Request headers Chrome:
Request headers firefox
This is the information reed.co.uk returns to you when accessing the results from their API:
You will need to include your api key for all requests in a basic
authentication http header as the username, leaving the password
empty.
Can anyone see why this would happen?

Translating a rest API call from angular to jQuery

Apologies if worded awkwardly, but I have to make an rest API call using jQuery. I've already made the call using angularJS before, but for this case I can't use that. I tried translating it to jQuery but I'm not getting the same results. Is there anything I'm doing wrong or am I missing information? I'm fairly new to jQuery so I feel as if I'm missing something crucial or misunderstood something.
Working code with angularJS:
var req = {
method: 'POST',
url: 'https://fakeurl.com/rest/v1/portal/user/' + $scope.email.value,
headers:{
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === '601') {
console.error('Token is invalid or has expired');
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error('Error calling rest endpoint',err);
reject();
});
} catch (ex) {
console.error('Exception calling rest endpoint',ex);
reject(ex);
}
});
};
My failing jQuery code:
var processCreate = function (email) {
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Try making an ajax call like this
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + 'glsFromWebsite';
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}

Passing parameters to routes in node.js

I am very new to Web Development. I used to do desktop development using WPF and C#. Now I am learning Node.js
I have a model called Party.js in which I define two exports as follows:
module.exports.getAllParties = function(callback){
Party.find().lean().exec(function(err, parties){
if (err) return callback(err, null);
callback(null, parties);
});
};
module.exports.getPartyByPartyCode = function(partyCode, callback){
Party.find({partyCode: partyCode}).exec(function(err, party){
if(err) return callback(err, null);
callback(null, party);
});
};
Now, I also have a route called Party.js in which I have two get methods as follows:
router.get('/', function(req, res, next){
//retrieve all parties from Party model
Party.getAllParties(function(err, parties) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"parties" : parties
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(parties);
}
});
}
});
});
router.get('/:partyCode', function(req, res, next){
Party.getPartyByPartyCode(function(err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"party" : party
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(party);
}
});
}
});
});
Now, when I use ajax:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
data = { partyCode : inputVal },
eReport = ''; //error report
$.ajax(
{
type: "GET",
url: "/Party",
dataType: "json",
data: data,
beforeSend: function(jqXHR, settings)
{
console.log(settings.url);
},
success: function(party)
{
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
My question is: Why the above ajax call returns me all the parties? I just want to get a party whose patyCode is passed in to the ajax call's data....
There are some errors in both your router response code and ajax function:
First correct your router code:
You were not using the provided party code in your model.
router.get('/:partyCode', function (req, res, next) {
var partyCode = req.param('partyCode');
Party.getPartyByPartyCode(partyCode, function (err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function () {
res.render('Party', {
title: 'Party',
"party": party
});
},
//JSON response will show all parties in JSON format
json: function () {
res.json(party);
}
});
}
});
});
Correct Ajax function calling
You must provide the party code as a URL parameter as your router indicates like that /:partyCode. Try the following:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
eReport = ''; //error report
$.ajax({
type: "GET",
url: "/"+inputVal,
dataType: "json",
data: data,
beforeSend: function (jqXHR, settings) {
console.log(settings.url);
},
success: function (party) {
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function (xhr, textStatus, errorThrown) {
alert('ajax loading error... ... ' + url + query);
return false;
}
});

Categories

Resources