Single Page Application? Login Page - javascript

I'm a little new to programming and I'm still beginning on working with a lot of the languages.
Currently, I'm working on a project that requires me to create a login page. With a successful login, the page will change to an "Account Info" page; however, this has to be a single page application. My professor specified that the server will have no concept of "page", and that moving from "Login" to "AccountInfo" will not change the page/URL.
How do I go about calling this? We've done introduction into Angular JS, but he's never done a tutorial on single page applications.
My .js for the login looks like this:
Home.LoginClick = function () {
$.ajax({
url: "Home/Login",
data: {
Username: $(".Username").val(),
Password: $(".Password").val(),
},
success: function (result) { alert(result);
if (deserializedData.Message == "Success")
Home.ChangeToAccountInfo();
}
});
}

Single Page application means that the client loads all the HTML in one shot, thus preventing your browser to refresh the page every time you click somewhere or go a different page. You can witness this in action by going into most websites.
It is considered best practices to use services for back end interaction. Therefore you should create a Auth. service managing your login. Create a function login - and logout. and then inject that service in your controller associated with the view thats displays the login form.
You should upon submission of the form call this login function. you can use ng-submit. after submitting the form the function that you injected in your controller will check with you backend to see if the user exist or not and then you can redirect the user toward the page you want.
You should look into the ui router for more details about how to handles your routes.

Related

I need to send and listen to events from a 3rd party JavaScript API

We are a social start-up and are given a great opportunity by one of the biggest banks in our country. Basically they will feature our website in their Mobile App, and users can access our website via their app in an iFrame. We are currently working on integrating a SSO log in flow between their app and our website, so users are logged in immediately when they open our website in their app.
For this, they have created an API that we're able to use. The API requires 2 main things to get the flow working:
send a pageLoaded() event when the DOM is ready, when this event is sent, we get returned a token to fetch the user's personal information with a public event.
send a pageReady() event when the backend logic processing is done (eg account created and user logged in).
They will show a spinner in their app, until the pageReady event is being sent to them.
My website uses PHP and JS (jQuery) as the main technologies. I am having a number of issues on how to implement this correctly.
This is the code I am using as of now, it works in a certain way, but it's very troublesome for the reasons mentioned below the code snippet:
$(document).ready(function(){
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host;
/*** Mobile App JS Code ***/
var receiver = new PostmessageExternalReceiver();
var sender = new PostmessageExternalSender();
receiver.addTokenEventListener(function (api, token, version){
if (api == 'init') {
$.ajax({
type: 'post',
cache: false,
url: baseUrl + '/login/abc/abcLogin',
data: {
'token': token
},
dataType: 'json',
success: function(response){
sender.pageReady();
window.location.replace(response.redirect_url);
}
});
}
});
sender.pageLoaded();
});
These are the problems that i'm not sure how to get around:
Since the sender.pageLoaded(); is in the jQuery document ready, and after performing the AJAX request, we are redirecting again to the same page (the homepage), because after the redirect, the user will be logged in and some extra blocks will show on the homepage. So if we are on the homepage again, the document ready will fire yet another sender.pageLoaded() event, and we are stuck in an infinite redirecting loop.
Right now I am including all 4 API javascript libraries provided by our third party, and my own javascript file including the AJAX request and the pageLoaded() and pageReady(). This is only applicable for users that come to our website via the 3rd party mobile app. For all other visitors in our website this is not applicable and requires extra resources to be loaded in when they're not used. (the ajax request will never be executed for them because a token will not be sent via the mobile app, but still we do not want to send a pageLoaded() for every visitor on our website, even if he is not from the mobile app.
This is a nice-to-have question: since we need to send the pageReady() after our PHP logic (via AJAX request) is done, we cannot do the redirect in PHP, so I return the redirect_url in my AJAX and then do the window.location.replace() method with the redirect URL. In the 3rd party app, this will cause the app to remove the spinner (on the pageReady() event) and show our website, but immediately afterwards we will redirect the user using the window.location.replace() , this causes a refresh of the page, and thus a small annoyance and not so smooth experience for the user. They expect after the spinner is gone that the website is immediately accessible. How would I go around this?
Thanks a lot in advance!

Access React app from other React app on the same page

I have a situation where I have written the front-end of my website as micro-services. Every functional section of my website is a react-habitat application bundled with css and html. I have done this so I can re-use these sections wherever I want on the site.
My problem is however in the checkout area I need to pass the customerId from the login application (on successful response) into the delivery address application so I can bring back the default address. I don't want to create a new application and duplicate the code for login and delivery address applications because I will need to use them elsewhere on the website.
So my question is. How can I pass this customerId from my login application to my delivery address application without a page reload? Is there a way to access a react application method from outside of that react application?
Login click handler:
clickHandler(e) {
e.preventDefault();
let payload = {"email":this.props.email, "password":this.props.password};
AuthenticationApp.login(payload).then((response) => {
if (this.props.referrer === "checkout") {
$("#checkout_login-register-tab").addClass("done");
$("#checkout_login-delivery-tab").removeClass("todo");
// Temporary hack to reload page until we can pass new user session into delivery/billing react app from here.
location.reload();
}
this.props.updateParentState({isLoggedIn: true});
})
.catch(function(response){
console.log("res2 - catch", response)
});
}
I have forced a page reload here so the delivery address application re-renders and picks up customerId from the service. I need a way to re-render the delivery application at this stage (from this separate application), either by accessing a function somehow or forcing the application to reset? Is this possible or is there a workaround other than a page reload?
You can do something like this:
loadDeliveryApp(data) {
ReactDOM.render(<DeliveryApp data={data} />, document.getElementById('delivery-app'))
ReactDOM.unmountComponentAtNode(document.getElementById("login-app"))
}
clickHandler(e) {
e.preventDefault()
// your login stuff
loadDeliveryApp(data)
}
Here is the working demo.
https://codepen.io/madhurgarg71/pen/dzgxMd
I'm the original creator of React Habitat.. all your applications can talk to each other via either a flux observer or something like redux.
I suggest flux for react habitat normally as the individual stores keep it light weight instead of one BIG store in redux where you might have dead code in a habitat situation.
You will need to create one common store that both your applications import so that if one changes it, the other will get the update. I can put a demo together later if that helps.

How to develop login/registeration in SPA application

My application has single page and implemented ngRoute for all tabs navigations.
Now, need to implement login and register. Post to that only, it should navigate to all tabs navigations.
I have confusion for below points:
1) Do I have to create create another one new page for login and register And post to login, do location.href and redirect to existed page which has all tabs navigations. (Is this valid for SPA based application?).
2) Or Do I have to add login and reigsteration on same page where all tabs navigation existed. (in this option, I am not sure, how I can hide all tabs until login or any security threats).
application is developed using angularjs and web api.
Please provide help here to show best approach.
thanks
Best approach is use ui.router instead of ngRoute.
Next is add root scope state change listener in app.run.js file
and add authentication check in there like below
var userInfo = authenticationService.isAuthenticated();
var isLogin = toState.name === "login";
if(isLogin){
if(userInfo)
e.preventDefault();
return;
}
if(userInfo === false) {
e.preventDefault();
$state.go('login');
}
hope this will help
You can have the login and register routes in the same page. Angular JS provides a $cookie service where in the cookies can be set.
Before the user log's in or register's, you can check for the cookie and hide the tabs using the directives which angular provides, for example: ng-if.
Once the user is logged in you can navigate to the home page using "$location.path" by mentioning your required path.

Meteor push/browserhistory won't go/reload to new page

So i am trying to make it so when the user hit one of the profiles, they get pushed to the profile page of the user the click on.
I am using currently using this set of code:
const self = this;
browserHistory.push({
pathname: '/users/' + self.props.user.username,
state: {_id: self.props.user._id}
});
Which just enter the correct url in the url bar. Although, the page does not load/reload. So i manually have to reload the page to get into the userprofile
Thank you for your time and help
tl;dr
You have to use a router which works properly with Meteor, right now FlowRouter is the best option to go
Reloading the page is not the expected behavior when route changes in Meteor, only the content of the page should be change to match the new route. Because apps created by Meteor are Single-page application, meaning that all content/code of your app are loaded at your first load.
After the first load, all required code for your app to work are already in client so when route changes the required content will be compute and put on the page, no request will be send to server.

How to integrate mailchimp using javascript

I have a web app and I will like to integrate mailchimp such that when a user clicks the signup button on the page, the user's email is added to a mailchimp subscription list but I'm having difficulty in doing so. The problem is, the button on the page is created in a javascript file using extjs. I do not have that much experience in developing web applications . I already downloaded the api for integrating with php. I saw this: " AJAX Mailchimp signup form integration " but it seems to have security issues.
Can anyone help explain how to go about this?
Have the ajax call directed to your server, with the user's email.
From there, use the API (you downloaded) to add the email, and return the outcome of their response to your client.
When you do it behind the scenes (your server to theirs), there is no security risk, as you are not exposing your API key.
Client side code:
Ext.Ajax.request({
url: 'add_mail_to_chimp.php',
params: {
email: theUser_sEmail
},
success: function(response){
var text = response.responseText;
alert ('yay' + text);
}
});

Categories

Resources