jQuery post within post done function - javascript

I'm trying to implement and figure out something that I've never done before. I have a sense how to do it but I'm not exactly sure how to do so...
So I have a button on my website where users perform authorization of my application. When user goes to xx website and authorizes my application I would like to perform a jQuery post to this xx website every 3 seconds checking whether the user has performed authorization of my app to use it.
If the response from the website is success i'd like to make the button enabled and clickable to proceed to final step to insert some record into the DB.
So the current code looks like this:
$(document).on("click", "#btnClick", function (e) {
$(this).prop('disabled', true);
e.preventDefault();
$.post("/GetMyData/GenerateSession")
.done(function (sessionID) {
window.open("https://example.com/Authorize?=" + data, "_blank");
$('#btnClick').hide();
$('#btnAuthorize').show();
$("#step2").removeClass("disabled").addClass("selected");
});
});
So as you can see when SessionID is generated in my aciton, I simply open up a new tab in my browser and take him to the corresponding website.
Now what I'd like to do in final step is remove this code where user himself has to click the button to authorize the application like this:
$(document).on("click", "#btnAuthorize", function () {
$.post('/GetMyData/StoreToken')
.done(function (data) {
if (data.result == "Success") {
window.location.href = '/Success';
}
});
});
So without having the user to perform this final step. I'd like to make my application do this for user and perform a post every 3 seconds once he #btnClick even has been triggered..
How could I do this with jQuery?
P.S. I'd like to do this because I've noticed that some people simply don't authorize the application for usage but still press this button ,and then errors occur, which is why I'd like to disable usre clicking this button unless he indeed authorized the app.

Something like this should do it.
var r = window.setInterval(function(){
$.post('/GetMyData/StoreToken')
.done(function (data) {
if (data.result == "Success") {
window.location.href = '/Success';
}
});
},3000);

If you want to perform some function every X time you have to use setTimeout/setInterval functions of javascript (https://www.w3schools.com/jsref/met_win_settimeout.asp)

Related

javascript "callbacks" across redirecting / after reloading

I've got a site (asp.net mvc razor) on wich some functionalities require authorization / login.
These functionalities can be started by clicking on a button for example.
By clicking on such a button, the system checks whether the user is logged in or not.
If not, the user is redirected to the login page where he can sign in.
After that he will be redirected to the initial page again without initiating the users action.
So heres the workflow:
->Page x -> button y -> click -> redirect to login -> login -> redirect to x.
The redirects are simple Url.Action() statements.
What I want to do is to dynamically redirect to the page the click came from and ideally jump to the senders selector in order to simplify things for users.
What possibilities do I have to achieve this?
Only things coming to my mind are quite ugly stuff using ViewBag and strings
Update:
Info: As storing session variables causes problemes concerning concurrent requests this feature is disabled solution wide so I cannot use session variables.
Besides: One of the main problems is, that I cannot sign in without making an ajax call or sending a form. And by sending a form or making an ajax call I loose the information about the original initiator of the action and the parameters.
I solved this by adding by adding this to all such actions in their controllers:
[HttpPost]
public ActionResult ActionA(Guid articleId, Guid selectedTrainerId)
{
//if user is not authenticated then provide the possibility to do so
if (!Request.IsAuthenticated)
{
var localPath = this.ControllerContext.RequestContext.HttpContext.Request.Url?.LocalPath;
var parameter = this.ControllerContext.RequestContext.HttpContext.Request.Params["offeringRateId"];
var returnUrl = localPath + "?articleId=" + parameter;
return PartialView("LoginForOfferingPreview", new LoginForOfferingPreviewViewModel
{
RequestUrl = returnUrl,
//this will be used in the view the request was initiated by in order to repeat the intial action (after login has been successfull)
Requester = OfferingPreviewRequester.CourseTrialAdd,
//this will be used in the view to initiate the request again
RequestParameters = new List<dynamic> { new { articleId = articleId },new { selectedTrainerId = selectedTrainerId }}
});
}
//actual action
SendBasketEvent(new CourseAddMessage
{
BasketId = BasketId,
OfferingRateId = articleId,
SelectedTrainerId = selectedTrainerId,
SelectedTime = selectedTime,
Participants = selectedParticipants,
CurrentDateTime = SlDateTime.CurrentDateTimeUtc(SlConst.DefaultTimeZoneTzdb),
ConnectionId = connectionId
}, connectionId);
return Json(JsonResponseFactory.SuccessResponse());
}
the hereby returned view for login contains following js code that is called if the login has been succesfull:
function onLoginFormSubmit(data) {
//serialize form containing username+pw
var datastring = $("#loginForm").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Login_Ajax","Account",new {area=""})',
data: datastring,
success: function (data) {
debugger;
// display model errors if sign in failed
if (!!!data.Success) {
$(".buttons-wrap").append('<span id="loginFormError" style="color:red;"></span>');
$("#loginFormError").append(data.ErrorMessage);
}
//call method of initiating view that will decide what to dow now
if (data.Success) {
var parametersObjectAsString = JSON.parse('#Html.Raw(JsonConvert.SerializeObject(Model.RequestParameters))');
window.onLoginForOfferingPreviewSuccess('#Model.RequestUrl', parametersObjectAsString, '#((int)Model.Requester)');;
}
},
error: function () {
}
});
}
this works fine as long sigining does not fail due to wrong username or pw.
If that happens, the view shows the errors but by now signing in again somethign really strange happens:
At first it seems to work exaclty like signing in successfully by the first time but then the ajax calls in window function onLoginForOfferingPreviewSuccess will always reach the error block without beeing able to tell you why.
Fiddler reveals weird http resonse codes like 227,556 or something
Thx

Implement a window to log in LinkedIn in MVC 5

I'm working in an mvc5 application where users have their own profiles, there should be a button which would open a pop-up window so that an individual user logs into LinkedIn as to sync his/her LinkedIn profile picture with our site's.
I don't think it can be implemented with modals because there's page navigation involved, so I thought about what I stated previously: a pop-up, is there a way to do this via javascript? Like, opening a pop-up and expecting a response to determine if the user logged in. If there is a better way, any info would be greately appreciated, my aim is to be able to sync the profile picture without having the user to get redirected to linked in from their profile view, I want them to change it from there and not leave the view. Is it possible to do so?
EDIT: To clarify, getting the image URL is not a problem, what I need to do is get the url from the profile window, which comes from the popup window.
You should have a look at their API it is well documented. You'll need additional permissions to retrieve the full profile. LinkedIn Profile API
I ended up using the Javascript SDK:
$('#btnSyncLinkedInPicture').on('click',
function () {
var myID = 3;
IN.User.authorize(function () {
IN.API.Raw("/people/~:(picture-url)").result(function (data) {
$.ajax({
type: 'GET',
url: '/MyController/MyAction?pictureUrl= ' + data.pictureUrl + '&id=' + myID,
success: function (result) {
$('#imgProfilePicture').attr('src', result);
}
});
}).error(function () {
});
});
});
First, we authorize the user which will open a pop-up window so that we authenticate, the SDK will abstract us from the OAuth process. After authenticating, we may want to write a callback function, in which we can already perform REST calls via the SDK methods (you can do it elsewhere as long as you have successfully authenticated).

How to add a signIn button in a website and update it based on user authentication

I am working on playframework but I believe this question is more about a general topic of web implementation. I am creating a website where I want to put my signin button on the top right corner of my home page and would like to update it based on user authentication.
i.e. if user is logged in there would be my profile and logout button and if not then there would be only signin button. I know how to implement it using different pages that uses different routes, in this case I can load complete page but I don't want to load complete page instead I would like to use popup window for signin/signup and want user to redirect back on the same page after signing in (click on signin -> signin form as a popup -> submit -> signed in) url shouldn't be changing in this process. I have seen this type of design in many popular websites but I don't know how to build one.
I did some research and found, we can do this using jquery's ajax call. With the help of ajax call we can request data from server in background (here I will request html) and update my current page DOM. In this case I am supposed to update DOM of my navbar's top right corner so I will request html for that part only but I don't know exactly how to do it? I am new to website designing, would it be a good design or there is other best way to do the same task?
It would be also appreciable if anyone can tell me how should I update link to my related css & js file page by page. I mean if some css file is not being used in a particular page how to remove reference to that and add a new one relevant to that page.
Sorry, If it looks fool of asking such basic questions here but I just want to clear my concept in web-designing and implementation. It would also be helpful if anyone can suggest me a book or link to read about these topics.
If I understood your question correctly, you were asking for help with the DOM -part of the equation?
Here's an example (see the JSFiddle, for the whole thing, as the current code expects the login button to be present at launch):
function login (logtype) {
var insertInput = function (value) {
document.getElementById('logincontainer').insertBefore(
document.createElement('input'),
document.getElementsByTagName('input')[0]);
var newButton = document.getElementsByTagName('input')[0];
newButton.type = 'button';
newButton.value = value;
if (value === 'logout') {
newButton.onclick = function () {login('logout');};
}
if (value === 'login') {
newButton.onclick = function () {login('login');};
}
if (value === 'myprofile') {
newButton.onclick = function () {window.location.href='http://jsfiddle.net/user/b00t/fiddles/';};
}
},
deleteInput = function () {
document.getElementById('logincontainer').removeChild(document.getElementById('logincontainer').lastChild);
};
if (logtype === 'login') {
var logIn = confirm('Login?');
if (logIn) {
insertInput('myprofile');
insertInput('logout');
deleteInput();
}
}
else if (logtype === 'logout') {
var logOut = confirm('Logout?');
if (logOut) {
insertInput('login');
deleteInput();
deleteInput();
}
}
}
JSFiddle

Can I send an alert from the server to the client in Meteor?

is there a way I can sent an alert from the server to the client? For example, a user clicks a button. That button calls a method on the server that checks if the user has been assigned an ID# yet. If the user has not been assigned an ID#, I want the browser to get an alert. I could easily do a check if I publish the ID# to the client, but the ID# is very sensitive and so I don't want to publish it. Any thoughts? Thank you in advance.
You can try something like the following:
1) On the client, create a button click listener that runs a Meteor method.
// CLIENT
Template.example.events({
'click button': function () {
Meteor.call('checkIfUserHasId', function (err, userHasId) {
if (!userHasId) {
alert('user has no id');
}
});
}
});
2) On the server, create the Meteor method that checks if the user has an id.
// SERVER
Meteor.methods({
checkIfUserHasId: function () {
// check if user has id
return true; // or false depending whether user has id or not
}
});
Meteor methods can be called remotely on the client but are defined on the server. This should help achieve what you want in terms of not exposing the id's when performing the check.

Removing someone from a user hash on navigating away from a page / page close

I'm building a Node.js / Socket.io project.
I have a hash of Users based on their websocket id. When a user makes the following request i'd like to add them to a group of users viewing that page.
app.get('/board/:id', function(req, res){}
I'd like to keep something like
Browsing = {
username : id,
username : id,
...
}
However i'm unsure how to remove a user lets say if they navigate off the page. Is there some kind of function that gets called upon page leave?
Partial Solution:The following seems to do the trick on Chrome:
$(window).unload(function(){
var username = $('#username').text();
var pid = currentProject;
var data = {
username: username,
id : pid
}
socket.emit('leaving-page', data);
})
... Is there some kind of function that gets called upon page
leave? ...
Yes, but it is not reliable.
The way the people keep track of who is online and who isn't, is usually like this:
Add the time when the user last refreshed/visited a page
set a limit to you consider them offline
You could intercept the event which corresponds to leaving a page. There are several ways to do it, have a look at the following links and let me know if any suits your needs and if I can answer any more explicit questions about them:
Intercept page exit event
Best way to detect when a user leaves a web page?
jquery unload
with the last link you could do something like this:
$(window).unload(function() {
//remove the user from your json object with delete json_object[key];
});
Hope this helps.
Since you're using Socket.io, the server will know when the user has left the page because the socket will be disconnected. Simply listen for the disconnect event.
io.sockets.on('connection', function (socket) {
...
socket.on('disconnect', function () {
// The user on `socket` has closed the page
});
});
Better yet, take advantage of namespaces and let Socket.io handle all of the connection/disconnection (it's doing it anyway -- no need to duplicate effort).
On the client,
socket = io.connect('http://example.com/pagename');
pagename need not point to a valid URL on your domain – it's just the namespace you'll use in the server code:
io.sockets.clients('pagename')
Gets you all of the clients currently connected to the pagename namespace.

Categories