Opening up new tab based on ajax response - Angular JS - javascript

On clicking a hyperlink,
{{id}}
I require something to open up in a new tab based upon the response (a flag, lets say - responseFlag) that I get from the ajax call.
Two methods I tried.
Note : Function is dependent on the id, so not using it on page load.
1.
$http.get(url).success(function(response) {
if(response.data.responseFlag==true){
$window.open("http://www.example.com");
}
else{
//perform something else other that window.open
}
});
The problem here is the 'Popup blockers' in the browsers (Chrome, Mozilla) - that keeps blocking them.
2.
var w = $window.open("","_blank");
$http.get(url).success(function(response) {
if(response.data.responseFlag == true){
w.location = "http://www.example.com";
}
else{
//perform something else
}
});
Here, if the 'responseFlag = true', it opens up in new tab. But as you might have guessed it, for 'responseFlag = false' too the tab opens up. I can use w.close() in the 'else' perhaps. But I think that's not a solution.
Help me out friends !

In your second example you're openning the new tab before doing the request, so it doesn't matter wich callback gets executed, you'll get a new window openned.
I don't see any reason why $window.open(...) works with your second example but not in the first, maybe is because the "_blank" parameter...
So, can you try this way?
$http.get(url).success(function(response) {
if(response.data.responseFlag == true){
var w = $window.open("","_blank");
w.location = "http://www.example.com";
}
else{
//perform something else
}
});

Related

Determine if the browser already opened an URL

We use an internal system (with FF as default browser)
We need to avoid that the user open the same URL in different tabs.
As the tabs share the same PHP session we get a mess.
So actually I'm looking to the way to check programmatically if certain URL is already opened in one of the opened tabs.
Client side (JS) or server side (PHP).
We use now the FF extension "Duplicate Tabs Closer" that helps.
But I'd prefer to keep full control (give warning, choose for which URL it works).
You can write cookie after your page loaded in the first tab, check it on the server side and show the user warning instead of actual page content if this cookie is set and the second tab is opened. To handle the case when a user closes the only opened tab you can remove that cookie in onbeforeunload handler.
Working off of Oleksandr's answer, you can store a map of number of times a url is opened, in a cookie. When a page is opened, increment the number or set it to 0. When a page is closed, decrement it or delete it.
function incrementTabsOpen() {
let tabsOpen = readObjCookie('tabsOpen') || {};
if (tabsOpen[window.location.href]) tabsOpen[window.location.href]++;
else tabsOpen[window.location.href] = 0;
writeObjCookie('tabsOpen', tabsOpen);
}
function decrementTabsOpen() {
let tabsOpen = readObjCookie('tabsOpen') || {};
if (tabsOpen[window.location.href]) tabsOpen[window.location.href]--;
if (tabsOpen[window.location.href] === 0) delete tabsOpen[window.location.href];
writeObjCookie('tabsOpen', tabsOpen);
}
// https://stackoverflow.com/a/11344672/3783155
function readObjCookie(name) {
let result = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (result) result = JSON.parse(result[1]);
return result;
}
function writeObjCookie(name, value) {
document.cookie = name + '=' + JSON.stringify(value);
}
and
window.addEventListener('load', function() {
incrementTabsOpen();
};
window.addEventListener('unload', function() {
decrementTabsOpen();
};

How to avoid javascript `window.open` triggering popup window alert

I'm trying to build an off-site notification function in jQuery. The script first checks if the link is an external link and then checks against a db table entries for exceptions. If the link is external and not on the list of exceptions, send the visitor to a notification page. If it is an external link that's on the exception list, then open the link in a new window without the notification page.
I'm using a jQuery $.post call to send the link info out to a php script that retrieves the exceptions and returns a yes or no for if it needs to go to the notification screen. Here's the code:
$('a').click(function(){
var url =$(this).attr('href');
if(url !== '#'){
// ignore links that don't 'go' anywhere
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.open(url);
return false;
}else if(url.substr(0,4) !='http'){
// check that the url isn't an internal link ('/page.php' for example)
return true;
}
// ajax script to check url is external and is there an exception. Returns as json object:
// link: link
// notify: true/false
$.post("/scripts/form_process.php", { action : 'offsite', link: url}, function(data){
if(data.notify == true){
// if visitors should be notified, redirect to the following link:
window.location= '/leaving-site?link='+encodeURIComponent(data.link);
return false;
}else{
// if the link is in the exception list, don't notify but do open the link in a new window:
window.open(data.link);
}
});
return false;
}
});
This is working fine except that so long as the window.open(url) command is inside the $.post success function, the browser is treating it like a popup instead of as a natural link. This seems to be a problem when using window.open inside the ajax call as far as I can tell. When I use it here:
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.open(url);
return false;
}
I don't get the pop up blocker.
I can't hard code the exceptions list and I have to check every link - I can't assume a class will be added to the links that need to be notified for example.
How can I open the external link in a new tab and avoid the popup blocker in this code?
The classic way to solve this is as follows:
Create the new window before the AJAX call:
var newWindow = window.open('', '_blank');
And in the success - you assign the URL to the new window like so:
newWindow.location.href = 'http://example.com';
Full example with your code:
$('a').click(function(){
var url =$(this).attr('href');
if(url !== '#'){
// ignore links that don't 'go' anywhere
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.location = url;
return false;
}else if(url.substr(0,4) !='http'){
// check that the url isn't an internal link ('/page.php' for example)
return true;
}
// ajax script to check url is external and is there an exception. Returns as json object:
// link: link
// notify: true/false
var newWindow = window.open('', '_blank');
$.post("/scripts/form_process.php", { action : 'offsite', link: url}, function(data){
if(data.notify == true){
// if visitors should be notified, redirect to the following link:
newWindow.location.href= '/leaving-site?link='+encodeURIComponent(data.link);
return false;
}else{
// if the link is in the exception list, don't notify but do open the link in a new window:
newWindow.location.href(data.link);
}
});
return false;
}
});

Why is my system logging out automatically?

I login into my website (running on localhost), and store the user id in a session variable
$_SESSION['user_id'] = $user_id;
The main page loads, and all is fine. I show the user id on the main page, so I'm sure of its value. When I load another page, using
php = 'some_php_file.php';
window.open(php,php);
The second page opens ok. But if I try to open the same page again, clicking on the same button on the main page, the system will logout. If I omit the second php in window.open() (using '' instead), I may have multiple copies of the same window (what I don't want), but no problem of automatic logout.
Any idea what may be happening?
EDIT: If I close the second window and repeat the process, I have no logout problem. I can close and reopen the second window as many times as I wish. The problem only happens if I try to open the second window, but it is already open. I can also open different 'second windows' (different php files). I'm only getting logged off if I try to open TWICE the same window.
EDIT 2: Seems I've found it. Before I call window.open(), I'm testing for the existence of the php file, using this function:
function fileExists(url){
var http = new XMLHttpRequest();
http.open('HEAD',url,true);
http.send();
return http.status != 404;
}
If I change the http.open() line to
http.open('HEAD',url,false);
it works! But the manual tells us to use 'true' in the third parameter... What should I do?
It seems to me that your fileExists function simply returns true all the time because it does not wait for the XHR to complete. Except when you specify async = false.
Time to read How to return the response from an asynchronous call? probably.
I have no clue what is the consequence of this always being true, as you do not share exactly what you do with that result.
Now if you want to "stick with the manual" and keep async = true (you should really indeed), then simply wrap your following code in a callback. E.g.:
function fileExistsAsync(url, callback){
var http = new XMLHttpRequest();
http.open('HEAD',url,true);
http.send();
http.onreadystatechange = function () {
if (http.readyState === 4) {
callback(http.status != 404);
}
}
}
fileExistsAsync(url, function (exists) {
console.log("async " + exists);
});
Demo: http://jsfiddle.net/52xqLfow/

Exit Popup Redirect With a Exception

I also dont like exit popups but i want to integrate if for a comming festival day so want to thanks my visitors and gave them some thing special.
I am this code below for redirect on exit.
var exitPop = false;
var nonFire = false;
window.onbeforeunload = function () {
if(!exitPop){
exitPop=true;
return 'Happy Festival Day!';
}
};
setInterval(function(){
if(exitPop && !nonFire){
nonFire = true;
window.location.href = 'http://google.com';
}
}, 200);
I am using this code below its basically redirect on doing a comment
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create',
function (response) {
window.location = "http://domain.com";
});
FB.Event.subscribe('comments.remove',
function (response) {
window.location = "http://domain.com";
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
and i dont want to show exit redirect to the my visitors who comment because its annoy my visitors i want that code execute only on clicking exit. so what code i should include which create exception of comment redirect and should not show popup to commenter
A popup window will only not be blocked if some link opens it. So if you are trying to load something on exit it won't work.
This is a working example: http://swip.codylindley.com/popupWindowDemo.html using a little library in jquery someone wrote. You can check out the source.
Basically, if the popup window opens onclick you should be fine, but in any other cases it will be blocked.
I am not sure how certain companies get away with it, but any sort of hacks eventually get plugged. One way I attempted to do it was to trigger an onclick action on a link and even that didn't work. So it is fairly fool proof.
You could do this by setting a cookie in javascript. You could do this with straight javascript but the code is shorter with the jquery.cookies plugin so ill demonstrate that method.
In your comment.create function, set a cookie to show that this user has made a comment:
FB.Event.subscribe('comment.create',
function (response) {
$.cookie('has_commented', 'true');
window.location = "http://domain.com";
});
Then check the cookie value on your exit function:
if($.cookie('has_commented') == true) {
return 'Happy Festival Day!';
}
Jquery Cookies plugin here: https://github.com/carhartl/jquery-cookie/blob/master/README.md
or if you want to do the same thing with straight javascript - same concept - but a bit messier.. info here: http://www.w3schools.com/js/js_cookies.asp

Export data using JSON

I need to export data in excel file.I am using JSON post for the same.Its working fine in every browser except IE. Have a look at my javascript code as follow:-
function ExportQueryData() {
var Qry = $("#txtQueryInput").val();
if ($.trim(Qry) == "") {
$("#txtQueryInput").addClass("error");
return false;
}
else
$("#txtQueryInput").removeClass("error");
var url = "/Reports/ExportQueryData";
var frmserialize = $("#frmQuery").serialize();
$.post(url, frmserialize, function(data) {
data = eval("(" + data + ")");
if (data.Success) {
url = "/Reports/Export";
var win = window.open(url, "DownloadWin", "resizable=0,status=0,toolbar=0,width=600px,height=300px");
win.focus();
win.moveTo(100, 100);
return false;
}
else {
Notify("DB Query", data.Message);
}
});
}
As per above code, i am calling /Reports/Export action using window.open. This pop up getting open for every browser except IE. In IE pop up get close simultaneously in 1 or 2 seconds.
I need to use JSON post because it validate input and then returns success status.I can validate my data only at server side.
Let me know if any information is missing here.
Your suggestion will be valuable for me.
Thanks.
I think you've got a pop up blocker situation... Frankly, I don't think opening up stuff in a pop up is a good idea anymore. Browsers seem to hate it.
You could instead show the user a link to the file, asking him to click to download.

Categories