How to retrieve oAuth Accees token from Redirect Window - windows

I am working on an app where i am communicating to Windows API. I am using oAuth 2.0 for the same.
Complete code has been done using JS/HTML5 only. However i am facing one issue,
whenever i request for access token, it opens a new windows with my redirect url appended with access token and other parameters. But the token is not sent back to my code. I have to manually copy the code and thus it defeats purpose of my application. Is there any way , when i click on button (that invokes my oAuth call), a new pop up window appears and redirects back to my called url with access token ?
here is what i have done so far:
var APPLICATION_CLIENT_ID = 'SOME_NUMBERS',
REDIRECT_URL = "http://www.myweb.com";
WL.Event.subscribe("auth.login", onLogin);
WL.init({
client_id: APPLICATION_CLIENT_ID,
redirect_uri: REDIRECT_URL,
scope: 'wl.skydrive_update',
response_type: "token"
});
WL.ui({
name: "signin",
element: "signInButton",
brand: "hotmail",
type: "connect"
});
function greetUser(session) {
var strGreeting = "";
WL.api(
{
path: "me",
method: "GET"
},
function (response) {
if (!response.error) {
strGreeting = "Hi, " + response.first_name + "!"
document.getElementById("greeting").innerHTML = strGreeting;
}
});
}
function onLogin() {
var session = WL.getSession();
if (session) {
greetUser(session);
}
}
var tokenAuth = //Adding Manually//
var apiURL = "https://apis.live.net/v5.0/me/";
var tokenAuthParam = "?access_token=" + tokenAuth;
And this is where i am stuck. Can anyone pls help. Also greetUser function is not working. I want this to work as client side only using js/html only. `

Not sure what you are trying to do with the tokenAuth. Got this working which should help you with the greeting part:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JScript Win 8 example</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<script type="text/javascript" src="/LiveSDKHTML/js/wl.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<div id="signin"></div>
<br />
<label id="infoLabel"></label>
<br />
id: <label id="id"></label><br />
firstname: <label id="first_name"></label><br />
lastname: <label id="last_name"></label><br />
fullname: <label id="name"></label><br />
gender: <label id="gender"></label><br />
locale: <label id="locale"></label><br />
<script>
WL.Event.subscribe("auth.login", onLogin);
WL.init({
scope: "wl.signin",
});
WL.ui({
name: "signin",
element: "signin"
});
function onLogin(session) {
var session = WL.getSession();
if (session.error) {
document.getElementById("infoLabel").innerText = "Error signing in: " + session.error;
}
else {
document.getElementById("infoLabel").innerText = "Signed in.";
WL.api(
"/me", "GET",
function (response) {
if (!response.error) {
document.getElementById("id").innerText = response.id;
document.getElementById("first_name").innerText = response.first_name;
document.getElementById("last_name").innerText = response.last_name;
document.getElementById("name").innerText = response.name;
document.getElementById("gender").innerText = response.gender;
document.getElementById("locale").innerText = response.locale
}
else {
document.getElementById("infoLabel").innerText = "API call failed: " + JSON.stringify(response.error).replace(/,/g, "\n");
}
}
);
}
}
</script>
</body>
</html>

Related

ERR_NAME_NOT_RESOLVED in OpenWeather Api Call

I'm putting together my first Api project and I'm using OpenWeather to request conditions for a city. When I run my code, I get "ERR_NAME_NOT_RESOLVED." I've checked and rechecked my URL formatting and I'm not getting any errors when running my code. Could anyone point me in the right direction?
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script defer src="./js/script.js"></script>
<title>Weatherd</title>
</head>
<body>
<h1>Weatherd</h1>
<form>
<input type="text" placeholder="Search by city"/>
<input type="submit" value="Search"/>
</form>
<main>
<p>Weather for</p>
<p id="weatherFor"></p>
<p>Temperature: </p>
<p id ="temp"></p>
<p>Currently feels like: </p>
<p id="feelsLike"></p>
<p>Conditions: </p>
<p id="desc"></p>
</main>
</body>
</html>
My JS
const $weatherFor = $('#weatherFor');
const $temp = $('#temp');
const $feelsLike = $('#feelsLike');
const $desc = $('#desc');
const $input = $('input[type="text"]');
let weatherData, userInput;
$('form').on('submit', handleGetData);
function handleGetData(event) {
event.preventDefault();
userInput = $input.val();
$.ajax({
url: 'https://www.api.openweathermap.org/data/2.5/weather?q='+userInput+'&APPID=15ff99dd07f18bda25869ab24d06891e'
}).then(
(data) => {
weatherData = data;
render();
},
(error) => {
console.log('bad request', error);
}
);
}
function render() {
$weatherFor.text(weatherData.weatherFor);
$temp.text(weatherData.temp);
$feelsLike.text(weatherData.feelsLike);
$desc.text(weatherData.desc);
}
It's been a while since the question was asked, but given the amount of visits this question has had so far, this answer might help someone.
const url = "api_url_here";
const result = await axios
.get(url)
.then((res) => {
const { status } = res;
return status && status == 200
? { ...res.data, status: 200 } // return data + status 200
: { status: 400 }; // create and return status 400 on error
})
.catch((err) => {
return { status: 400 }; // create and return status 400 on error
});
// work with the returned status
if(result.status == 200) {
// success
} else {
// error
}
I used axios, but the idea is very much transferable to Fetch Api or Ajax.

Fetching JSON data on Ajax button click in .net core

I am new to Ajax. Trying to fetch JSON data returned from Get webAPI from controllers but on button click nothing rendering on View.
This is how my view look like
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
var id = $(this).attr(id);
$.ajax({
url: '/api/employee', type: "GET", dataType: "json",
data: { id: id },
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.FirstName + ' ' + val.LastName;
ulEmployees.append('<li>' + fullName + '</li>')
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
This is the JSON data returned by webapi
Can anyone help me what went wrong here? Thanks in advance.
Below should work:
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
var id = $(this).attr('id');
fetch('/api/employee?id=' + id)
.then((resp) => resp.json())
.then(function(data) {
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.firstName + ' ' + val.lastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
})
.catch(function(error) {
console.log(error);
});
});
});

Load Vue Componet via AJAX

I'd like to load Vue Component via AJAX dynamically and render its template.
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
alert(url);
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
var mainContent;
fetch('/vue/actions/?content_type=json&action='+action).then((response) => {
if(response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
}).then((json) => {
this.$router.push({ path: '/vue/actions/', query: { action: json.action }});
// this.mainContent = json.template;
console.log(json.template);
this.dynamicComponent = json.template;
}).catch((error) => {
console.log(error);
});
}
},
created: function () {
this.actions();
}
})
Initial Page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script type="text/javascript" src="/js/vue.min.js"></script>
<script src="/js/vue-router.js"></script>
</head>
<body>
<template><div><component :is="dynamicComponent"></component></div></template>
<div id="mainContainer" v-html="mainContent"></div>
<script type="text/javascript" src="/js/main.js"></script>
</body>
</html>
Component I'd like to load via AJAX:
Vue.component('dynamicComponent', {
template: '<div>Dynamic Component!</div>'
});
Is it possible to load such Vue Componet and render its template (with an ability to use Vue data bindings in the Component template)?
Here is how I got what I need:
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
Vue.component('dynamic-component', (resolve) => {
import('/vue/actions/?content_type=javascript&action='+action).then((component) => {
resolve(component.default);
});
});
}
},
created: function () {
this.actions();
}
})
Main/Initial Page Body:
<body>
<div id="mainContainer">
<dynamic-component></dynamic-component>
</div>
<script type="text/javascript" src="{{.__web_root_folder}}/js/main.js"></script>
</body>
Component code that I'm loading when needed:
export default {
template: '<div>Async Component! {{.test}}</div>',
data () {
return {
test: 'Works!'
}
}
}
Thanks to #MazinoSUkah !

vuejs & http.get call not working

I'm starting to work with vuejs and I'm trying to make a http get call without sucess. I've tried several example showing how to do that but I get the following error in my console: this.$http is undefined.
html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/css/uikit.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.21/js/uikit-icons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.19.1/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.19.1/vis.min.css" rel="stylesheet" type="text/css"/>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<p v-bind:title='message'>
{{ message }}
<p>
<button v-on:click='changeView("matrice")'>get data</button>
</div>
</body>
<script type="text/javascript" src="/front/lala_web/matrice.js"></script>
</html>
js
var app = new Vue({
el: '#app',
data: {
message: 'Empty data'
},
methods:{
changeView: function(v){
this.$http.get('/view/'+v)
.then(function(resp){
this.message = resp.data;
})
.catch(function(){alert('Error')});
}
}
})
I'been able to get a http get call working using the following js, but doing so doesn't change data.message value of vuejs and I get the following error data is not defined.
js
var app = new Vue({
el: '#app',
data: {
message: 'Empty data'
},
methods:{
changeView: function(v){
var viewUrl = '/view/'
$.ajax({
url: viewUrl+v,
method: 'GET',
success: function (resp) {
if (resp.error == false){
console.log(resp)
data.message = resp.data
}
},
error: function (error) {
console.log(error)
}
});
}
}
})
You need to reference this.message not data.message. Also, you'll need to save a reference to this outside the scope of the ajax call, since this in the success handler doesn't refer to the Vue instance:
changeView: function(v){
var viewUrl = '/view/'
var self = this;
$.ajax({
url: viewUrl+v,
method: 'GET',
success: function (resp) {
if (resp.error == false){
console.log(resp)
self.message = resp.data
}
},
error: function (error) {
console.log(error)
}
});
}

Kendo UI Grid sortable (and other properties) not working

I'm trying to configure a Kendo grid and I'm having issues when trying to add properties such as sorting, grouping, etc. The grid works until I add the property, then it doesn't display any of the data. I have looked at the documentation on Kendo's site and it looks as if I have everything the same as theirs but obviously I'm nissing something.
Here is the View:
#model ExampleKendoUI.Models.HeaderVm
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>#Model.Name</div>
#section scripts {
<script>
// Output the data as JSON
var podata = #Html.Raw(Json.Encode(ViewBag.LineItems));
</script>
<div id="poGrid" class="k-content">
<script>
$(document).ready(function () {
$("#poGrid").kendoGrid({
dataSource: {
data: podata
},
// sortable:true, *** Uncommenting this will break the grid ***
columns: [
{
field: "Description",
title: "Desc"
},
{
field: "Quantity",
title: "Quantity"
}
]
});
});
</script>
</div>
}
Here is the controller:
namespace ExampleKendoUI.Controllers
{
public class SampleController : Controller
{
//
// GET: /Sample/
public ActionResult Index(int id)
{
var header = new HeaderVm()
{
Id = id,
Name = "Req ID"
};
var results = new List<PoLineVm>()
{
new PoLineVm()
{
Id = 1,
Description = "Some Product",
Quantity = 1.5
},
new PoLineVm()
{
Id = 2,
Description = "Another Product",
Quantity = 4.0
},
new PoLineVm()
{
Id = 3,
Description = "Last Product",
Quantity = 20
},
};
ViewBag.LineItems = results;
return View(header);
}}}
Here is the _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
<link href="~/Content/kendo/2012.3.1114/kendo.default.min.css" rel="stylesheet" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
<script src="/scripts/kendo/2012.3.1114/kendo.core.min.js"></script>
<script src="~/Scripts/kendo/2012.3.1114/kendo.data.min.js"></script>
<script src="~/Scripts/kendo/2012.3.1114/kendo.grid.min.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
You haven't included the required JavaScript files and the JavaScript error means that kendoSortable is missing. Check the documentation for the required JavaScript files: http://docs.kendoui.com/getting-started/javascript-dependencies

Resources