after login unable to stay on current page - angular-ui-router

i am using $stateChangeStart instead of routechangestart , the problem i am facing is that after login whenever i refresh page i get redirected to home page,here is my code?
$rootScope.$on(‘$stateChangeStart’, function (event,next, toState, toParams,fromState, fromParams, options) {
if(next.name === “product.login” && $rootScope.authenticated) {
event.preventDefault();
} else if (next.name && next.data.requireLogin && !$rootScope.authenticated ) {
event.preventDefault();
$rootScope.$broadcast(“event:auth-loginRequired”, {});
}
else if (next.name && !AuthSharedService.isAuthorized(next.data.requiredRole)) {
event.preventDefault();
$rootScope.$broadcast(“event:auth-forbidden”, {});
}
}
);
$rootScope.$on(‘event:auth-loginConfirmed’, function (next,tostate,toparams, data,event)
{
console.log(‘login confirmed start for ‘ + tostate);
$rootScope.loadingAccount = false;
var nextLocation = ($rootScope.$state.current.name? $rootScope.$state.current.name : “frontProduct.productgrid”);
Session.create(tostate);
$rootScope.account = Session;
$rootScope.authenticated = true;
$state.go(nextLocation);
});
i just want to stay on current page.help me!

Hope you doing well
you have to also specify if user is not authenticated then where user redirect
if (!$rootScope.userloggedIn && !$rootScope.authenticate) {
$state.go("login");
event.preventDefault();
}
else{
$state.go("home");
}
look like this.
Hope this help you.

found answer,
$rootScope.$on('$stateChangeStart', function (event,next, toState, toParams,fromState, fromParams) {
if(next.name === "product.login" && $rootScope.authenticated) {
event.preventDefault();
} else if (next.name && next.data.requireLogin && !$rootScope.authenticated ) {
if(next.name!="product.login"&&next.name!=""){$window.localStorage.setItem('url',next.name);}
event.preventDefault();
$rootScope.$broadcast("event:auth-loginRequired", {});
}
else if (next.name && !AuthSharedService.isAuthorized(next.data.requiredRole)) {
event.preventDefault();
$rootScope.$broadcast("event:auth-forbidden", {});
}
}
);
$rootScope.$on('event:auth-loginConfirmed', function (next,tostate,toparams, data,event,$stateProvider) {
console.log('login confirmed start for ' + tostate);
$rootScope.loadingAccount = false;
$rootScope.$state.current.name : "frontProduct.productgrid");
Session.create(tostate);
$rootScope.account = Session;
$rootScope.authenticated = true;
$state.go($window.localStorage.getItem('url'));
$window.localStorage.remove('url');
});
i just want to know is this a correct way.

Related

Bootstrap Selectpicker not refreshing

When a user clicks the edit icon the contents of a selectpicker are updated then refreshed. Then the selectpicker's value is updated, then refreshed again, but for some reason it is not updating with the selected value.
Everything works fine when I manually enter in the the same code in the console.
$('#IncWidgetId').val(864)// the value used when breaking in console
$('#IncWidgetId').selectpicker('refresh')
I have ensured that the selectpicker is updated with the new option values along with confirming the deferred is firing in the proper order.
As a double check, I also have separated the .selectpicker('refresh') to make sure it didn't try to fire before the option was selected due to async, but it is still not updating the selectpicker with the selected value.
$(document).on('click', '[id^=EditWidgetId-]', function () {
var id = $(this).attr('id').split('-')[1];
var mfg = $(this).data('mfg');
var widgetid = $(this).data('widgetid ');
var mfgSelect = $('input[name=mfg][value="' + mfg + '"]');
mfgSelect.prop('checked', true);
$.when(LoadWidgets(mfg)).then(function () {
console.log('then function');
$('#IncWidgetId').val(widgetid );
}).done(function () {
console.log('done function');
$('#IncWidgetId').selectpicker('refresh');
});
$('#modalWidgetNew').modal('show');
});
function LoadWidgets(mfg) {
var r = $.Deferred();
console.log('before ajax');
r.resolve($.ajax({
url: '/Widgets/FilterWidgetsDropdown',
type: 'GET',
cache: false,
data: { mfg: mfg },
success: function (partial) {
$('#IncWidgetDDArea').html(partial);
$('#IncWidgetId').selectpicker('refresh')
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
})).done(function () {
console.log('after ajax');
return r.promise();
});
}
What am I missing?
There was such an issue in old versions of this plugin.
Try to destroy it and initialize again. Something like this:
$('#IncWidgetId').selectpicker('destroy');
$('#IncWidgetId').selectpicker();

How to add my textbox item in the table? in master detail form

I am using MVC to create my Master Detail form, i have tried this to add my detail record in the to show my detail record in the form so that when user click Add button detail data itself shows in a table.
JQUERY is not working
This is my View:
#section script{
//date picker
$(function () {
$('#orderDate').datepicker({
datepicker: 'mm-dd-yy'
});
});
$(document).ready(function()
{
var orderItems = [];
//Add Button click function
$('#add').click(function () {
//Chk Validation
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden')
}
if (!($('#quantity').val().trim() !== '' && !isNaN($('#dvch_nar').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden')
}
if (!($('#itemName').val().trim() !== '' && !isNaN($('#dvch_cr_amt').val().trim()))) {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden')
}
if (!($('#rate').val().trim() !== '' && !isNaN($('#dvch_cr_amt').val().trim()))) {
isValidItem = false;
$('#rate').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#rate').siblings('span.error').css('visibility', 'hidden')
}
//add item to list if valid
if (isValidItem) {
orderItems.push(
{
ItemName: $('#itemName').val().trim(),
Quantity:parseInt$('#quantity').val().trim(),
Rate: parseInt$('#rate').val().trim(),
Total: parseInt($('#quantity').val().trim())* parseFloat($('#rate').val().trim())
});
//clear fields
$('#itemName').val('').focus();
$('#quantity').val('');
$('#rate').val('');
}
//populate order item
GeneratedItemsTable();
}
);
//save button click function
$('#submit').click(function () {
//validation order
var isAllValid = true;
if(orderItems.length=0)
{
$('#orderItems').html('<span style="color:red;">Please add another item</span>')
isAllValid = false;
}
if ($('#orderNo').val().trim() == '')
{
$('#orderNo').siblings('span.error').css('visibility', 'visible')
isAllValid = false;
}
else {
$('#orderNo').siblings('span.error').css('visibility', 'hidden')
}
if ($('#orderDate').val().trim() == '') {
$('#orderDate').siblings('span.error').css('visibility', 'visible')
isAllValid = false;
}
else {
$('#orderDate').siblings('span.error').css('visibility', 'hidden')
}
//if ($('')
//save if valid
if (isAllValid){
var data={
Date: $('#orderNo').val().trim(),
Remarks: ('#orderDate').val().trim(),
Description:$('description').val().trim(),
orderDetails:orderItems
}
}
$(this).val("Please Wait...");
$.ajax(
{
url: "/Home/SaveOrder",
type:"post",
data:JSON.stringify(data),
dataType:"application/json",
success:function(d){
//check is successfully save to database
if(d.status==true)
{
//will send status from server side
alert('successfully done.');
//clear form
orderItems=[];
$('#orderNo').val('');
$('#orderDate').val('');
$('#orderItems').empty();
}
else{
alert('Failed');
}
},
error :function(){
alert('Error:Please Try again.');
}
}
);
});
//function for show added item
function GeneratedItemsTable()
{
if(orderItems.length>0)
{
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>')
var $tboday = $('<tbody/>');
$.each(orderItems,function(i,val)
{
var $row=$('<tr/>');
$row.append($('<tr/>').html(val.ItemName))
$row.append($('<tr/>').html(val.Quantity))
$row.append($('<tr/>').html(val.Rate))
$row.append($('<tr/>').html(val.Total))
$tboday.append($row);
});
$table.append($tboday);
$('#orderItems').html($table);
}
}
}
);
</script>
}
thanks for quick response
Try this
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
//Date Picker
$(function () {
$('#orderDate').datepicker({
dateFormat : 'mm-dd-yy'
});
});
$(document).ready(function () {
var orderItems = [];
//Add button click function
$('#add').click(function () {
//Check validation of order item
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'visible');
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'visible');
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
isValidItem = false;
$('#rate').siblings('span.error').css('visibility', 'visible');
}
else {
$('#rate').siblings('span.error').css('visibility', 'hidden');
}
//Add item to list if valid
if (isValidItem) {
orderItems.push({
ItemName: $('#itemName').val().trim(),
Quantity: parseInt($('#quantity').val().trim()),
Rate: parseFloat($('#rate').val().trim()),
TotalAmount: parseInt($('#quantity').val().trim()) * parseFloat($('#rate').val().trim())
});
//Clear fields
$('#itemName').val('').focus();
$('#quantity,#rate').val('');
}
//populate order items
GeneratedItemsTable();
});
//Save button click function
$('#submit').click(function () {
//validation of order
var isAllValid = true;
if (orderItems.length == 0) {
$('#orderItems').html('<span style="color:red;">Please add order items</span>');
isAllValid = false;
}
if ($('#orderNo').val().trim() == '') {
$('#orderNo').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#orderDate').val().trim() == '') {
$('#orderDate').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderDate').siblings('span.error').css('visibility', 'hidden');
}
//Save if valid
if (isAllValid) {
var data = {
OrderNo: $('#orderNo').val().trim(),
OrderDate: $('#orderDate').val().trim(),
//Sorry forgot to add Description Field
Description : $('#description').val().trim(),
OrderDetails : orderItems
}
$(this).val('Please wait...');
$.ajax({
url: '/Home/SaveOrder',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
//clear form
orderItems = [];
$('#orderNo').val('');
$('#orderDate').val('');
$('#orderItems').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#submit').val('Save');
}
});
}
});
//function for show added items in table
function GeneratedItemsTable() {
if (orderItems.length > 0)
{
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th><th></th></tr></thead>');
var $tbody = $('<tbody/>');
$.each(orderItems, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.ItemName));
$row.append($('<td/>').html(val.Quantity));
$row.append($('<td/>').html(val.Rate));
$row.append($('<td/>').html(val.TotalAmount));
var $remove = $('Remove');
$remove.click(function (e) {
e.preventDefault();
orderItems.splice(i, 1);
GeneratedItemsTable();
});
$row.append($('<td/>').html($remove));
$tbody.append($row);
});
console.log("current", orderItems);
$table.append($tbody);
$('#orderItems').html($table);
}
else {
$('#orderItems').html('');
}
}
});
</script>

Ajax code not working only validation worked

Here is the JS Fiddle
My Ajax code not working i dont know how..
I used ajax below code many time but this time not working
please help me..
only this code run inside the ajax code
if(!validateee()) return false;
If validation code remove then ajax run
Ajax Code
$('#body-enquiry').submit(function(e){
e.preventDefault();
if(!validateee()) return false;
$(this).find(":submit").prop("disabled", true);
var form = $(this);
var post_url = 'enquiry-entire-mail.php';
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(data) {
alert('Submited');
}
});
});
you forgot to return true at the end of your function that is the issue.
return true;
this you need to write in you validateee function .
please find update here : https://jsfiddle.net/qref356z/6/
you updated validateee function, update below code it will work i checked it at my end
function validateee() {
var name = document.popbody.namebody.value;
var email = document.popbody.emailbody.value;
var number = document.popbody.numberbody.value.length;
var msg = document.popbody.msgbody.value.length;
alert('msg5');
if(name.trim() == "") {
alert("Please Fill Name");
document.popbody.namebody.focus();
return false;
}
alert('msg4');
if(name<3) {
alert("invalid Name");
document.popbody.namebody.focus();
return false;
}
alert('msg3');
if(email=="") {
alert("Enter Your Email");
document.popbody.emailbody.focus();
return false;
}
alert('msg2');
if(number=="") {
alert("Enter Your Number");
document.popbody.numberbody.focus();
return false;
}
alert('msg1');
if(number<9) {
alert("Your Mobile number at least 10 digit");
document.popbody.numberbody.focus();
return false;
}
alert('msg');
if(msg == "") {
alert("Enter your Message");
document.popbody.msgbody.focus();
return false;
}
return true;///you need to add here
}

Ajax request does not work if i dont write return false at the end

This is my validation function written on button click.
function chk_add_area()
{
var areaCountry=$('#areaCountry').val();
var areaCity=$('#areaCity').val();
var area=$('#area').val();
if(areaCountry.trim()=="")
{
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
else //if(areaCountry.trim()!="" && areaCity.trim()!="" && area.trim()!="")
{
$.ajax({
url:'ajax.php?action=duplicatearea&areaCountry='+areaCountry+'&areaCity='+areaCity+'&area='+area,
type:'get',
success:function(res)
{
if(res=="exists")
{
$('#err_div').html("Area already exists");
}
}
});
//return false;
}
/* else
{
return true;
} */
}`
if i uncomment return false,it works properly but then the form does not submit on success & i cant proceed further.
Can anyone tell me why?
You need a return false if the area already exists, otherwise drop through.
You don't need to return true; just exiting from the function works fine.
function chk_add_area() { // onsubmit handler
var areaCountry = $('#areaCountry').val().trim();
var areaCity = $('#areaCity').val().trim();
var area = $('#area').val().trim();
if ( areaCountry == "" ) {
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
if ( areaCity == "" || area == "" ) {
$('#err_div').html("Please Select City and Area");
return false;
}
$.ajax({
url: 'ajax.php?action=duplicatearea&areaCountry=' + areaCountry +
'&areaCity=' + areaCity + '&area=' + area,
type: 'get',
async: false, // EDIT: added Dec 30
success: function(res) {
if ( res == "exists" ) {
$('#err_div').html("Area already exists");
return false;
}
}
// allow form submit to proceed
}
Also, I recommend using POST instead of GET because GET is cacheable. Someone might add the same area twice.

Worklight: Challenge-handler not working as expected

I used sample challenge handler that comes with Form Based Authentication module. I modified it as per my requirements. In my App, I have one Landing (home) page , where i have link to a login page. Now i want it to function when user click on the login button. I face various problems here:
On first click on Login button, it does authenticate with WL
Server but then it is unable to proceed further to execute login
function logic.
after first click, i have to 2nd time click on
Login button. At 2nd login click it execute login function
perfectly.
When I log out,either it is NOT
removing session from server or what? It only execute log-out
function code (given below). But again after the specified session
time out, it prompts 2nd/3rd time and shows "time out message".
Although user is not loged in again. he is already log-out.
Purpose: I want App to only login when user click on Log-in button, but with just one click. and when i log-out Or time out, it should not keep session active OR shows "session timeout" message after the specified time again & again.
My Challenge Handler:
var aahadAppRealmChallengeHandler = WL.Client.createChallengeHandler("myAppRealm");
var isLandingPage=false , islogout=false;
aahadAppRealmChallengeHandler.isCustomResponse = function(response) {
WL.Logger.debug("I am here >> 1");
if (!response || response.responseText === null) { return false; }
var indicatorIdx = response.responseText.search('j_security_check');
if (indicatorIdx >= 0){ WL.Logger.debug("return true "); return true; }
else {
if(isLandingPage && $.trim($('#fldloginUserID').val()) !="" && $.trim($('#fldloginUserPassword').val()) !="" ) {
WL.Logger.debug("WL.Client.isUserAuthenticated()=" + WL.Client.isUserAuthenticated("myAppRealm"));
if(WL.Client.isUserAuthenticated("myAppRealm")) { WL.Logger.debug("return false "); return false; }
else { WL.Logger.debug("return true "); return true; }
}
WL.Logger.debug("return false "); return false;
}
};
aahadAppRealmChallengeHandler.handleChallenge = function(response) {
WL.Logger.debug("I am here >> 2");
var indicatorIdx = response.responseText.search('j_security_check');
var suc = response.responseText.search('success');
WL.Logger.debug("I am here >> 3 - indicatorIdx =" + indicatorIdx + " Success =" + suc + " - isLandingPage=" + isLandingPage +" islogout=" +islogout);
if (isLandingPage){
if (suc >= 0 ){
WL.Logger.debug("I am here >> 4 - isLandingPage=" + isLandingPage +" suc="+suc);
var reqURL = '/j_security_check'; var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
aahadAppRealmChallengeHandler.submitLoginForm(reqURL, options, aahadAppRealmChallengeHandler.submitLoginFormCallback);
}else {
WL.Logger.debug("I am here >> 5");
WL.SimpleDialog.show(DialogMessages_en.SessionExpired_Tile, DialogMessages_en.SessionExpired_Description ,
[ { text : 'Close', handler : function () {
if(busyIndicator.isVisible())
busyIndicator.hide();
isLandingPage = false; userLogout();islogout=true;
$.mobile.changePage("#landingPage" , { transition: "slide"});
} } ]);
}
}
else {
WL.Logger.debug("I am here >> 6 - isLandingPage=" + isLandingPage +" re-Login Again");
if(indicatorIdx < 1) {
var reqURL = '/j_security_check'; var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
aahadAppRealmChallengeHandler.submitLoginForm(reqURL, options, aahadAppRealmChallengeHandler.submitLoginFormCallback);
}
}
};
aahadAppRealmChallengeHandler.submitLoginFormCallback = function(response) {
var isLoginFormResponse = aahadAppRealmChallengeHandler.isCustomResponse(response);
if (isLoginFormResponse){ isLandingPage=false; aahadAppRealmChallengeHandler.handleChallenge(response); }
else {isLandingPage=true; aahadAppRealmChallengeHandler.submitSuccess(); WL.Logger.debug("aahadAppRealmChallengeHandler.submitSuccess()"); }
};
$('#logindone').bind('click', function () {
WL.Logger.debug(" Button Clicked -Before isLandingPage=" +isLandingPage);
isLandingPage=true;
var reqURL = '/j_security_check'; var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
aahadAppRealmChallengeHandler.submitLoginForm(reqURL, options, aahadAppRealmChallengeHandler.submitLoginFormCallback);
loginAuthenticateUser();
});
my Login Function
function loginAuthenticateUser() {
WL.Logger.debug("Calling loginAuthenticateUser()....");
busyIndicator.show();
if ($.trim( $("#fldloginUserID").val()) !="" && $.trim( $("#fldloginUserPassword").val()) !="") {
authenticateLDAPUsers( $.trim( $("#fldloginUserID").val().toLowerCase() ) , $.trim( $("#fldloginUserPassword").val() ));
}else {
if(busyIndicator.isVisible())
busyIndicator.hide();
simpleDialogDemo(DialogMessages_en.LoginFailed_MsgTitle , DialogMessages_en.LoginFailed_MsgDescription);
}
}
Log-out Function
function userLogout() {
WL.Logger.debug("Logout....");
WL.TabBar.setVisible(false);
WL.Client.logout('myAppRealm', {onSuccess: function(){} });
$.mobile.changePage("#landingPage" , { transition: "slide"});
var options = {onSuccess: function() {WL.Logger.debug("collection closed");}, onFailure: function() { WL.Logger.debug("collection closing failed"); } };
WL.JSONStore.closeAll(options);
}
authenticationConfig.xml (Realms)
<realm loginModule="Strongme" name="myAppRealm">
<className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
<parameter name="login-page" value="login.html" />
</realm>
Worklight.properties
serverSessionTimeout=5
Any suggestion please.
Thanks
In case of FormBasedAuthentication you need to trigger authentication before actually submitting credentials. Therefore you need to call WL.Client.login("realm-name") in your app.
In case authentication requires immediately on app startup - call WL.Client.login(..) in your wlEnvInit or wlCommonInit function. In case it is requires on a later stage - call it once you need it.

Resources