Open new tab onclick JS event using handler ashx - javascript

I have a login button with onclick event...onclick = "login();"
I successfully logged in ...but I wanted to open new tab instead.
This is my javascript:
login = function() {
if ($("#UserName").val().length == 0) {
return;
}
if ($("#Password").val().length == 0) {
return;
}
var logindata = new Object();
logindata.UserName = $("#UserName").val();
logindata.Password = $("#Password").val();
locustraxx.showLoading("loginformDiv");
locustraxx.doAjaxPostback('//example.com/LoginHandler.ashx', logindata, null, null,
function(data, textStatus, jqXHR) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (data.success == true) {
if ($("#Remember").is(':checked')) {
$.cookie('remember', $("#UserName").val() + '|' + $("#Password").val(), {
expires: 36500,
path: '/'
});
}
var retUrl = $.QueryString("ReturnUrl");
if (retUrl == undefined || retUrl == null) {
window.location.replace(data.data, '_blank');
} else {
window.location.href = decodeURIComponent(retUrl).replace(/\~~/g, ".");
}
if (isChrome) {
// clearCookies();
}
return false;
} else {
alert(data.message);
$("#UserName").focus();
}
}, null,
function() {
login.hideLoading("loginformDiv");
});
}
I tried _blank... window open, but to no avail

Could you please specify better what you have tried so far in theory you should be OK with:
window.open('https://www.google.com', '_blank');
If It isn’t working please specify the error output of the console.
There is also a known issue in which the browser opens a new window instead of a new tab, but that has to do with the user preferences, nothing to do about that. See here.

Related

Angularjs problem: cannot resolve variable, but variable exists

I'm doing a project for University where I have a login for a website and I have to implement some operations. My issue is to maintain user session when a user is logged; so, if I open the website in a new tab, I want to be logged with the account of the main tab.
This is my angularjs code for the loginController:
mainAngularModule
.controller('LoginCtrl', ['$scope', '$state', 'AuthFactory',
function ($scope, $state, AuthFactory) {
let ctrl = this;
ctrl.authRequest = {username: 'admin', password: 'password'};
ctrl.doLogin = doLoginFn;
ctrl.authMessage = '';
//check if user already logged
let logSession = localStorage.getItem(("authinfo"));
if(logSession == null){
console.log("logSession null");
}
if(logSession == undefined){
console.log("isundefined");
}
if(logSession != null){
console.log("not null");
console.log("usern: " + logSession.username);
//console.log("authinfo authorities: " + logSession.authorities)
AuthFactory.setJWTAuthInfo(logSession);
$state.go("dashboard.home");
}
console.log("login authinfo: " + localStorage.getItem("authinfo"));
let sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key === 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
} else if (event.key === 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
}
function doLoginFn() {
console.log("doLoginFn");
var requiresLogin = $state.jwtToken;
console.log("requireLogin: " + requiresLogin);
AuthFactory.sendLogin(ctrl.authRequest, successCB, errorCB);
function successCB(response) {
let authInfo = response.data;
console.log("data = " + response.data.all);
let header = response.headers();
authInfo.jwtToken = header['authorization'];
console.log("authInfo", authInfo);
// AuthFactory.user.username = authInfo.username;
// AuthFactory.user.role = authInfo.role;
let debugJWT = true;
//if (debugJWT) {
if (true) {
console.log(authInfo);
console.log("username: " + authInfo.username);
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("jwtToken: " + authInfo.jwtToken);
console.log("userType: " + authInfo.userRole);
console.log("ended.");
}
AuthFactory.setJWTAuthInfo(authInfo);
//console.log("authinfoo1234: " + authInfo);
// localStorage.setItem("authinfo",authInfo);
console.log("authorities: " + authInfo.authorities);
$state.go("dashboard.home");
}
function errorCB(response) {
let error = response.data;
if (error && error.status === 401) {
ctrl.authMessage = error.message;
}
else {
console.error(response);
ctrl.authMessage = 'No response from server';
}
}
}
}
]);
I have a very strange problem: I'm using Intellj, and it tells me in lines
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("userType: " + authInfo.userRole);
but if I comment lines with localStorage.setItem and localStorage.getItem, console prints on output correct userType and userRole; if I add those lines, console prints out this message:
TypeError
​
columnNumber: 17
​
fileName: "http://localhost:63342/ISSSR_frontend/app/scripts/service/AuthFactory.js"
​
lineNumber: 59
​
message: "authInfo.authorities is undefined"
I really don't understand, why it says me that it cannot resolve variable, but it can print out it?
Unfortunately I could not deploy your code would you please prepare codepen or flickr.
Some points that I can mention is below:
instead of use console.log("username: " + authInfo.username); use : console.log('username : ',authInfo.username)
Instead of JSON.stringify(authInfo.authorities) use : angular.toJson(authInfo.authorities,true)
Also console.log(response) to see what it returns.

What is the best way to render PartialView to a Layout Page in MVC?

There is a layout page in my MVC5 project and I want to render all the page contents (partial views) by clicking menu links (hyperlink) on the left side as shown below. There are some methods using Ajax, etc. but I am not sure which approach meets my needs best. Is there any example regarding to this problem containing the Layout page and Controller methods?
You have to first wrap your body content in div and assign any id to it:
<div id="divContentArea">
#RenderBody()
</div>
Now in Script Menu click event:
$(".menuLinkItem").click(function (e) {
e.preventDefault();
var controllerName = $(this).attr('data-controllername');
var actionName = $(this).attr('data-actionname');
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
//Open url in new tab with ctrl key press
if (e.ctrlKey) {
window.open(url, '_blank');
event.stopPropagation();
return false;
}
$.ajax({
url: url,
type: 'POST',
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
$("#divContentArea").html(data);
},
error: function (xhr) {
}
});
});
Controller:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public PartialViewResult Index()
{
if (HttpContext.Request.HttpMethod == "GET")
{
return View();
}
else
{
return PartialView();
}
}

Login using Json

I am trying to develop a login process using json.
My problem is that when I make many login attempts , parameters are not overriden but concatenated.
Below is the code I'm writing.
I do not see where the problem is.
Thank you in advance .
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function() {
var json = this.responseText;
Titanium.API.info("step 1 done");
var response = JSON.parse(json);
if (response.status == true) {
Titanium.App.Properties.setString("key", response.key);
alert("Success");
} else {
alert("Email or password wrong");
}
};
function doConnVerif() {
if ($.email.value != '' && $.password.value != '') {
loginReq.open("POST", "URL");
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
} else {
alert("Enter email and password");
}
}
By your question I can't grasp the full aspect of the problem, but definitely a good idea would be only allow one login attempt at a time.
Something like:
var pendingRequest = false;
// ...
if(!pendingRequest) {
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
pendingRequest = true
}
// ...
loginReq.onload = function() {
pendingRequest = false
// ...

How to use shortUrl as parameter in href on each condition

I'm using jquery-bitly-plugin for shorten some URLs and I'm doing in this way:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
shorten = bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine
// I got something like http://bit.ly/1DfLzsF
return shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
Then I tried this:
console.log(shorten);
But got Undefined, why? How do I assign the var in order to use in other places?
EDIT: adding extra information around the problem
This info will clarify a bit what I'm trying to do with my question so I have this code which allow to share some content in social networks on click event:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0];
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + url;
}
else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + url;
}
else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
return false;
}
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
});
As you may notice url is common to share-facebook and share-twitter. I need to shorten that URL and pass back to the href on each possible choice. For shorten the URL I'm using jquery-bitly-plugin as follow:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine I got
// something like http://bit.ly/1DfLzsF
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
How I can use shortUrl in href parameter? Do I need to repeat the code on each condition in order to use execute the action at onSuccess event from shorten() method? How do you deal with this?
To assign to a variable:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
shorten = shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
The method shorten doesn't have a return on source code of plugin.
IMPROVED ANSWER
Based on your edite post, this is the correct answer on how to use it the shortUrl:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0],
opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + shortUrl;
} else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + shortUrl;
} else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
}
if ($(this).data('category') != 'share-mail')
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
return false;
});
As I said in a comment, you need to figure out a future for the shortened URL. This future here is "open a window with this URL". Here is a quick pseudocode:
function openWindow(shortUrl) {
window.open(shortUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}
$('.share-item').click(function () {
if ($(this).data('category') == 'share-mail') {
...
return;
}
if (....twitter...) {
href = ...
} else if (....facebook....) {
href = ...
}
bitly.shorten(url, {
onSuccess: openWindow,
onError: function(err) {
...
}
});
}
(I made the openWindow future into a separate function to make it obvious, but it could just as well have been left inline.)

jQuery/AJAX: Code works in Chrome but not IE

I'm working on a validation form, I'm sending the data from the html fields with JS pulling the validation with a php document and sending it back via AJAX, it works pretty fine in Chrome but not Internet Explorer (I'm testing it in IE9):
function Checkfiles() {
var fup = document.getElementById('flUpload');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
var chkext = ext.toLowerCase();
if(chkext=="gif" || chkext=="jpg" || chkext=="jpeg" || chkext=="png") { return true; } else { return false; }
} // Checkfiles
function Checksize() {
var iSize;
if ($("#flUpload")[0].files[0]){ iSize = ($("#flUpload")[0].files[0].size / 1024);}
if(Checkfiles()==true && iSize <= 51.200) { return true; } else { return false; }
} //Checksize
$(document).ready(function() {
$("#ff1").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function (response) {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response)=='b' && Checksize()==true) {
this.submit(); // submit, bypassing jquery bound event
}
else {
if (Checksize()==true) {
$("#ajax_call_val").html('<div id="validation"><ul>'+response+'</ul></div>');
} else {
if(response!='b') {
$("#ajax_call_val").html('<div id="validation"><ul>'+response+'<li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>');
} else { $("#ajax_call_val").html('<div id="validation"><ul><li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>'); }
}
}
}
});
});
});
Any wonder why is not working in IE? Thanks in advance.

Categories

Resources