Get hold of json content that is being sent to Jquery - javascript

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),

Related

How to save JavaScript sessionStorage to django

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)
}
})

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');
}
});
});

Calling Outlook API to Add event to outlook calendar using ajax call

I need to Add an event from my database to outlook calendar for which I have been trying to make an ajax call to the outlook auth API first which looks like this
$scope.authorizeOutlook = function () {
let redirect = 'http://localhost:51419';
let clientId = 'xxx';
var authData = 'client_id=' + clientId + '&response_type=code&redirect_uri=' + redirect + '&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fcalendars.readwrite%20&state=12345';
debugger
$.ajax({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
type: 'POST',
host: 'https://login.microsoftonline.com',
contentType: "application/x-www-form-urlencoded",
contentLength: "600",
data: authData,
success: function (response) {
debugger;
alert(response.status);
//alert("success");
},
error: function (response) {
alert(response.status);
//alert("fail");
}
});
}
But I am getting response status as 0. What does that mean? Where am I doing it wrong?
If you use Oauth2.0, you need to add " token-type: Bearer ".
Reference from:
Get access tokens to call Microsoft Graph

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 get CSRF token Value at javaScript

I have requirement like that, when I send request, CSRF-token should be send with it. I Explore some SO questions, But I can't find Solution.
I have written Code like bellow to add token when request being sent,
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', "xyz12345");
//this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
return send.apply(this, arguments);
}
This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.
I have tried ajax function as below .
`
$.ajax({
type: "POST",
url: "/test/"
//data: { CSRF: getCSRFTokenValue()}
}).done(function (data) {
var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
if (csrfToken) {
var cookie = JSON.parse($.cookie('helloween'));
cookie.csrf = csrfToken;
$.cookie('helloween', JSON.stringify(cookie));
}
$('#helloweenMessage').html(data.message);
});
But it is not Yet Worked.
So my question is:
How to get js side CSRF-Token Value?
you need to do this in new Laravel
var csrf = document.querySelector('meta[name="csrf-token"]').content;
$.ajax({
url: 'url',
type: "POST",
data: { 'value': value, '_token': csrf },
success: function (response) {
console.log('value set');
}
});
I get my CSRF Token by this way,
By adding function :
$.get('CSRFTokenManager.do', function(data) {
var send = XMLHttpRequest.prototype.send,
token =data;
document.cookie='X-CSRF-Token='+token;
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token',token);
//dojo.cookie("X-CSRF-Token", "");
return send.apply(this, arguments);
};
});
Where CSRFTokenManager.do will be called from CSRFTokenManager Class.
Now It is adding token in header and cookie in every request.

Categories

Resources