Href to Onclick redirect - javascript

I have research this topic through the community, although I cannot find an answer. I am using Bronto's direct add feature (attempting to use it), The documentation isn't that great.
In summary, the href link subscribes the user on the email list. The only problem is that this link opens a new page. When I want the user to stay on the same page. I though about doing a redirect, when clicking the link, though I am not sure if that would work.
I have tried this:
//Html
<a id="subscription" href="http://example.com">Subscribe</a>
// Jquery
$("#emailsubscribe").click(function(e){
e.preventDefault();//this will prevent the link trying to navigate to another page
//do the update
var href = "http://example.com";
//when update has finished, navigate to the other page
window.location = "href";
});
The goal is that I am trying to make it where the user clicks on the link, it subscribes them to the email list, but immediately redirects them back, without opening another window.

You're looking for AJAX. This allows you to make requests without actually navigating to a page. Since you're using jQuery
$("#emailSubscribe").click(function (e) {
e.preventDefault();
$.get("http://www.myurl.com", function (data) {
//All done!
});
});

You have 3 options:
Do an AJAX request to subscribe the user
$('#emailsubscribe').on('click', function () {
$.get('/email-subscribe/' + USER_ID, function () {
// redirect goes here
window.location = 'REDIRECT_URL';
});
});
Use an iframe and when the iframe has loaded close the iframe (ugly, hacky, not recommended)
Have the subscribe page redirect the user back. Aka do the common messages of "You have been subscribed. Redirecting back in 5seconds...". You would need to pass the redirect link to the subscribe page, aka
window.location = '/subscribe/USER_ID?redirect_to=/my-redirect-page'

You need to refer the var, instead of typing another string to redirect.
//Html
<a id="subscription" href="http://example.com">Subscribe</a>
// Jquery
$("#emailsubscribe").click(function(e){
e.preventDefault();//this will prevent the link trying to navigate to another page
//do the update
var href = "http://example.com";
//when update has finished, navigate to the other page
window.location = href; //<<<< change this.
});

Related

Ajax - doesn't change URLs

I made the contents of the page change using Ajax, but the problem is the site url stays the same, therefore it doesn't load the page at all, just the text on it. So for example, I click on the Login link and the content changes, but the url stays on site/, not site/login. The actual login form does not load because it doesn't even call it, only loads basic text. How can I fix that ?
P.S. Using Zend for the website
Script:
$(document).ready(function() {
$('a').click(function() {
var toLoad = $(this).attr('href');
$('#content').load(toLoad);
return false;
});
});
Ajax does not reload the page or load another page so the url does not change when you make an ajax request.
If you want the url to change, for example so that your ajax-filled pages can be shared and bookmarked, you need to change the url manually.
You can use the html5 history API for that.
A simple example:
// we need the click event here
$('a').click(function(e) {
// cancel default click action using `e`
e.preventDefault();
var toLoad = $(this).attr('href');
$('#content').load(toLoad);
// check if the html5 history api is available in the browser first
if (window.history && window.history.pushState) {
// push the state to the url in the address bar
history.pushState({}, e.target.textContent, e.target.href);
}
});
Now the url in the address bar should change to the url of the link but the link is not really followed, instead the ajax request was made.
Note that you also need to make sure that all your urls load correctly. This is just a simple example and by the look of it your linked url would not load a complete page.
Check for example the documentation on mozilla.org for more information.

Prevent back button load the hash in url instead on clicking a button

I have a website where the subscription form will appear when user click on a subscribe button and will add # to the url(http://signature-bravo.dev/#subscribe_form).
My question is how to make the page reload (usually when user click back button on browser) without showing the subscription form even the url is still http://signature-bravo.dev/#subscribe_form. It just appear when user click on a subscribe button.
How to archive this?
Thanks in advance!
If you are using jQuery this should work:
$(window).on('unload', function(){
window.location.hash = '';
});
It still leaves the '#', but nothing after.
If you don't want to use jQuery, you can use this code:
window.onunload=function(){
window.location.hash = '';
}

Making ajax call on navigating away from page

I am working on a site that has multiple links to other sites. What I want is to send an ajax call to report that the user is going away when someone clicks and navigates away from the page. I put an alert on click of the links, which works but for some reason the controller never gets the ping.
Any assistance will be appreciated on how to achieve it.
Can't be done.
When you go to navigate away, there is only one event that can catch that, the onbeforeunload event, and that is quite limited in what it can do.
Not to mention there are other ways of leaving the page without navigating away:
Losing network connection
Closing the browser.
Losing power.
The only thing you can do is to set up a heartbeat kind of thing that pings the server every so many milliseconds and says 'I'm Alive.'
Depending on what you are trying to do, there is usually a better option, however.
You can try to simply set click event handler which will check the href attribute of every link before navigating. If it goes to another website, the handler sends AJAX request and then (after server responding) redirects to the page.
var redirect = '';
$('a').click(function() {
if (this.href.host != document.location.host) {
if (redirect) return false; // means redirect is about to start, clicking other links has no effect
redirect = this.href;
$.ajax({
url: '/away',
success: function(){document.location.href = redirect;}
});
return false;
});
However it can't work properly, if user has opened your page in multiple tabs.
The only reliable way to do this these days is by hooking (i.e. add event listener) your code in so called sendBeacon method from Beacon API on beforeunload event (i.e. when user tries to navigate away from page).
The navigator.sendBeacon() method asynchronously sends a small amount of data over HTTP to a web server. It’s intended to be used for sending analytics data to a web server, and avoids some of the problems with legacy techniques for sending analytics, such as the use of XMLHttpRequest:
<script>
var URL = 'https://your.domain/your-page.php';
// on 'beforeunload'
window.addEventListener('beforeunload', function (event) {
navigator.sendBeacon(URL);
// more safely is to wait a bit
var wait_until = new Date().getTime() + 500;
while (new Date().getTime() <= wait_until);
});
</script>
You can try:
$(window).on('beforeunload', function(){
return "This should create a pop-up";
});
You can achieve it by capturing clicks on all the links on the page (or all the relevant links) and then call ev.preventDefault() on it to prevent the browser from navigating directly to that page.
Instead, you can make an AJAX call to your server and when that call returns, you can set window.location to the URL the user was trying to navigate to.
Here is a workaround you could try.
At the loading of the page, use jquery to move all href attributes to tempHref attribute. Then, attach a method to catch the click event.
This way, clicking on the links will not automatically move to the intended destination.
When the click occurs, simply perform the ajax call, and then using javascript, move to the other page.
$('a').each(function () {
var link = $(this);
link.attr('tempHref', link.attr('href'));
link.removeAttr('href');
});
$(document).on('click', 'a', function ()
{
//perform ajax call;
location.href = $(location).attr('tempHref');
});

How to handle every link click on a page in JS or jQuery?

People create their own websites using WYSIWYG creator i give them. These websites have links inside of them. Also they can explore the HTML of the website and put there their own links.
I would like now to handle every link click occurring in website created with my creator and log it to my server. I know how to pass the data from JS or jQuery to PHP server. But what i need to know is how to handle the moment when person clicks a link, postpone the redirection for some moment, and in this time get the url and title of this link and send to my PHP server.
So how to handle every link click (or location change) on website that structure i don't know and get the link and title of the link clicked?
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var title = $(this).attr('title');
// Send your data to php
if ($(this).attr('target') === '_blank') {
window.location.href = href; // redirect to href
} else {
window.open(href);
}
});
jQuery("a").click(function(){
var href = $(this).attr('href');
$.post('/', {link: href}).then(function(){ document.location = href; });
return false;
});
just a try
To intercept every link, just place this function somewhere that every page has access to (header/footer/etc.):
$('a').click(function(event) {
event.preventDefault();//To prevent following the link
//Your logic. attr('href') and attr('title')
});
You can use jQuery to do this. Use the on event and bind to the click event of a element. You can then do an event.preventDefault(); do your logic and then continue as normal by getting the href from the target.
Why you want to wait till logging is completed for the redirection. Let it be an asynchronous call so that user don't need to wait. If you want to have your server page in a different domain, to tackle the cross domain ajax issue, use jsonp datatype.
$('a').click(function() {
$.ajax({
url:"yourwebsite/loggingpage.php?data="+$(this).attr("href"),
dataType: 'jsonp' // Notice! JSONP <-- P (lowercase)
});
});
and in loggingpage.php, you can read the request data and log it to your persistent storage or wherever you want.

How to capture the destination url in onbeforeunload event

I want to use onbeforeunload to give a message to users before leaving certain pages.
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
Thanks
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
No, definitely not. The onbeforeunload event tells you only that the page is about to be unloaded, but not why.
It depends on how the user is leaving the page.
If they are typing an url in the address bar - then you're out of luck. As far a I know there's no way to capture the url of an address bar jump.
If they are clicking on a link contained somewhere on the page - that you can use the click event to capture the url and then decide how you want to handle things.
I posed a similar question
How can i get the destination url of a link on the web page in the javascript onbeforeunload event?
because I had a project to fix a wholesale order form. During the process of filling out an order my client's customers would go back to the catalog to check on a product's detail page and loose the current information on their order form.
By using the code below (which uses JQuery though I'm sure you could create the same thing in pure Javascript if you had to) I could tell when the user clicked a link that would leave the order form and then give them the option of opening the link in a new window/tab or loading the url in the current window and loosing their form data, or just returning to the form. This code works with all of the major browsers, at least their more recent versions.
$('body a').click(function(e) {
//if link references a page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});

Categories

Resources