How to save JavaScript sessionStorage to django - javascript

I have an Sdk to call which returns an applicationID that I need to store in my django application so that if the user is approved, then he can move to the next page. I am trying to save in JS sessionStorage than pass the data to another html page where I'm using ajax to pass it to my django views. The problem is that I need to have this data unique for the user that is logged in.
How can I link this data to the current user logged in and so on?
const widget = window.getidWebSdk.init({
apiUrl: '',
sdkKey: '',
containerId: "targetContainer",
flowName: '',
onComplete: (data) => {
console.log(JSON.stringify(data))
let appId = data;
console.log(data)
sessionStorage.setItem("appId", JSON.stringify(appId))
window.location.href = "/kycsubmit";
return;
},
onFail: ({ code, message}) => { console.log("something went wrong: " + message )},
});
second html page:
let application = JSON.parse(sessionStorage.getItem("appId"));
let kycStatus = application.applicationId
$.ajax({
type: "GET",
dataType: "json",
url: `api/application/${kycStatus}`,
headers: {
'Content-Type': 'application/json',
'X-API-Key': '',
},
success: function(data) {
document.getElementById("test").innerHTML = data.overallResult.status
document.getElementById("test-1").innerHTML = application.applicationId
console.log(data.overallResult.status)
}
})

Related

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

localStorage won't store data

I have a demo of a simple Login and Logout application with access token. If the user haven't login yet and they try to access other page, which mean access token is null, they will be direct back to Login page. I use sessionStorage to store user token and it work fine. When I try using localStorage, my application won't work anymore. It still login in but for an instance moment, it direct me back to the Login page like my token isn't saved at all. It still generate new token after successfully login so I guess it having something to do with localStorage.
Edit: I just checked back and they both storage my token but I can't parse it to other pages with localStorage.
My Login Page Code:
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
//sessionStorage.setItem("accessToken", response.access_token);
localStorage.setItem("accessToken", response.access_token);
window.location.href = "User.html";
//$('#divErrorText').text(JSON.stringify(response));
//$('#divError').show('fade');
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
Other page base code:
if (localStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
Are you sure that response.access_token does not come null?
You can check it from the development tools in Chrome (Windows: Ctrl + Shift + i or macOs: command + option + i)> Application > Storage > Local Storage:
As you can see the value can be set null.
I hope it helps.
localStorage supports only string values. Chances are response.access_token might not be a string value. So try this instead:
localStorage.setItem("accessToken", JSON.stringify(response.access_token));
And While retrieving,
JSON.parse(localStorage.getItem("accessToken"))
Try to save object in localstorage use following method (as shown in https://stackoverflow.com/a/2010948)
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
And in your code we can do it like this
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
var obj= { 'accessToken': response.access_token};
localStorage.setItem(JSON.stringify(obj));
window.location.href = "User.html";
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});

Get hold of json content that is being sent to Jquery

That's how I reach when I send some values that are specified in my input and therefore they need to send to a API.
When I try to send them to the monkey, my monkey tells me that nothing has been sent.
At my console.log(token), it tells me what data is available and I also agree that it all fits together. But the problem is just that it has to come over to my API.
function PayStripe() {
// Open Checkout with further options:
handler.open({
name: 'XXX ',
description: 'XX abonnement',
currency: "dkk",
amount: $('#HiddenPrice').val() * 100,
email: $('#Email').val()
});
};
// Close Checkout on page navigation:
$(window).on('popstate', function () {
handler.close();
});
var handler = StripeCheckout.configure({
key: 'pk_test_xxxx',
locale: 'auto',
token: function (token) {
token.subscriptionId = $('#SubscriptionId').val();
token.City = $('#City').val();
token.Postnr = $('#Postnr').val();
token.Mobil = $('#Mobil').val();
token.Adresse = $('#Adresse').val();
token.CVRVirksomhed = $('#CVRVirksomhed').val();
console.log(token.subscriptionId);
console.log(token);
$.ajax({
type: "POST",
url: "/api/Stripe",
contentType: "application/json",
data: token,
success: function (data) {
//window.location.href = '/Subscriptions/Succes';
alert(data + "Succes")
},
error: function (data) {
console.log(data + "Error");
},
dataType: 'json'
});
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
Where the problem lies is that the API is by no means able to get informed information from jquery. so it's like it can not / will receive it.
[HttpPost]
[Route("api/Stripe")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromForm] JObject token)
When I grab the token that I need for example. then I do this here:
var SubscriptionId = (int)token.GetValue("subscriptionId");
When you set contentType: "application/json", you need to stringify the data to json yourself
data: JSON.stringify(token),

SharePoint send email with javascript on add list item

I like to send an email to the administrator when a user adds a item to my List. I already changed the NewForm for the list and execute the add item with:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
Now in my SharePoint the email notification on Lists has been disabled by the company. So I'd like some code to send an email automatically after the user added an item.
I already have the username of the person who added the item.
var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
The email has to be send to an address of the companies outlook server. An SMTP can be used.
Marco
Here is a little code snippet to send email using javascript.
function getUserEmail(){
$.ajax({
url:spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid("+_spPageContextInfo.userId+")?$select=Email",
headers:{"Accept": "application/json;odata=verbose","content-type": "application/json;odata=verbose"},
success:function(result){
var email = result.d.Email;
sendEmail("xxxx#email.com", email, "body", "subject");
}
});
}
function sendEmail(from, to, body, subject) {
var siteurl = _spPageContextInfo.webServerRelativeUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': {
'type': 'SP.Utilities.EmailProperties'
},
'From': from,
'To': {
'results': [to]
},
'Body': body,
'Subject': subject
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log(data);
},
error: function (err) {
console.error(err);
}
});
}
But it also depends on your scenario. Can you give us more details about:
I already changed the NewForm for the list and execute the add item with:
How did you proceed?
Are you working on on-premise or online instance?
It seems that it was still possible to set an alert on a list when an item was added. So that solved my problem.

How to prevent sending duplicate request with a single click in AngularJs

I have an angularJs application that has an api call with a click on a link . but everytime i click on the link it sends 2 same api calls to the server. Why this occurs and how can i resolve this.
my service is like: SomethingService
function getData() {
return apiSettings.getApiInformation().then(function (response) {
var url = response.data.Url + "/odata/Something?$expand=Something";
var data = {
url: url,
type: "GET",
token: response.data.Token,
data: {},
async: true,
cache: false,
headers: {
"accept": "application/json; charset=utf-8",
'Authorization': 'Bearer ' + response.data.Token
},
dataType: "json",
success: {},
error: {},
complete: {},
fail:{}
};
return $http(data);
});
}
Api Settings :
angular.module('myApp.services')
.factory('apiSettings', apiSettings);
apiSettings.$inject = ['$http'];
function apiSettings($http) {
return {
getApiInformation: function () {
return $http.get(baseUrl+ '/api/GetApiInformation', {cache: true});
}
}
}
SomethingController:
var vm = this;
function getSlots(filterCriteria, selectedValue) {
somethingService.getData().then(function (response) {
if (response && response.value.length > 0) {
vm.someData = response.value;
}
});
View:
clicking on this link calls getSlots that sends duplicate request
<a ui-sref="something" class="action-icons" id="slotNav"><i class="fa fa-square-o fa-fw"></i>
something
</a>
this view displays data
<div ng-repeat="data in vm.someData">
<p> {{data.Name}}</p>
</div>
Issue: For a single trigger browser sends duplicate requests like the following. the first call doesn't have callback but the second call has callback:
someuls?$expand=something&_=1432722651197
someuls?$expand=something&_=1432722651197
I had a similar problem which I fixed by checking this answer. I had declared "ng-controller" in HTML as well as routed to it using routeProvider. Fixed the issue by removing the "ng-controller" property in HTML.
Hope this helps.

Categories

Resources