javascript load url in background - javascript

I remember a couple of years a go, I used an hack from somewhere to update link hits in the background. What I remember is that I had an onclick event on my links that triggered a javascript function which tried to load an image or something (this is the hack), but instead of an image (or whatever it was) you put in an url like 'mysite.com/updatehits.php?id=3'
Hope this makes sense :S

Say you have this link:
<a id="link" href="foo.html">Click for foo</a>
You want the user to visit that link, but transparently call a 'hit counter' via ajax. That can be done like so:
$("#link").click(function(e) {
// prevent the link from getting visited, for the time being
e.preventDefault();
//update the counter
$.post("counter.php" {incrementCounter: this.href}, function(resp) {
if(resp == "success") {
alert("updated");
} else {
alert("failed");
}
// updated. Now visit this link as normal
window.location.href = this.href;
});
});
Still, I think counting views is something best done on the server side. Plus, this will more than likely cause an annoying perceptible delay to the user upon visiting links.

Related

Best Way to Load Pages w/o Reloading

I am working on building a website that will not reload to a new page every time a link is pressed. I want to make something kind of like all enterprise/popular websites. (When looking in the network dev tab: notice that youtube page doesn't completely reload when you click on a link, same with google, same with Facebook for the most part. They all usually just reload the page content and nothing else.)
I would like only the HTML between the body tags to be changed (nothing else: no js,css, no head tags, etc).
It would seem like it is pretty easy. Currently, I am just using ajax to go out and fetch the html of the page, and load that into the body. Done! Not so fast... Three things (my code is at the bottom)
The js includes are located at the bottom of the page, right before the closing body and html tags. When looking in the network tab, it shows that the same js is always gotten again and parsed again. How do I prevent that?
Some pages will not load styles that are set. (note that all css, js, etc. scripts are the same for every page)
I want to make sure that the page is completely reloaded if the user leaves the website.
I am not sure if I am looking for a fix to the way I am doing it, but probably just a completely better different way to do it.
Here is my code:
$('a').on('click', function () { //on click of any <a> tag
var where = $(this).attr('href'); //gets url of the <a> attribute
$.ajax({
type: "GET",
url: where, //where is the variable defined above
success: function(a) {
// load next page
history.pushState({urlPath: where},"",where); //changes the link of the webpage
$('body').html(a); //changes the body of the webpage
document.title = $('#title').text(); //changes the title using some weird irrelevant method
}
});
return false;
});
$(window).on('popstate', function() {//on click of the back or forward button
$.ajax({
type: "GET",
url: window.location.href, //the url is the url that the back or forward button is set to
success: function(data) {
//console.log();
$('body').html(data);//replaces data
document.title = $('#title').text();//changes title using weird irrelevant method
}
});
});

Href to Onclick redirect

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.
});

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');
});

Changing div#content without reloading using Jquery

I have been reading this board all night and I haven't found anything that quite hits the answer I need on the head, so I will ask.
Here's the basic idea of what I'm doing.
On Page Load, fade in, and display the default page.
User Clicks Navigation Link (a.navLink).
div#content fades out, calls a function to redirect.
div#content fades in with new content.
I have it at about 90% however, it's not quite right.
I am using a PHP Switch to manage content on the site using the $_GET superarray. My basic switch structure is as follows:
switch( $_GET['page'] ){
default:
//DISPLAY HOME PAGE
break;
case "story":
// DISPLAY STORY
break;
case "contact":
// DISPLAY CONTACT
break;
}
and so on...
The JQuery I'm using to perform the Fade In / Fade Out Action is as Follows:
$("#content").css("display", "none");
$("#content").fadeIn(1000);
$("a.navLink").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("#content").fadeOut(500, redirectPage);
function redirectPage() {
window.location = linkLocation;
}
});
The current code successfully fades out, changes pages and fades back in, but the problem is the site reloads, causing the rotating banner I have at the top of the page to restart. Also, the page starts back at the top as if the site had just been loaded. I know that this likely needs an AJAX function, but I have very little experience using AJAX (I often avoid it like the plague).
It is very important that I use the Switching structure I have in place, and I haven't had much success hashing it. The URL that I would be working with is DOMAIN.COM/index.php?page=pageName. Again, this structure is very important and cannot be changed.
Any insight on this would be great.
(Again, I understand this question type may have been asked before, but i feel that I need one line at most, and I'm trying to find out what that is)
Instead of
window.location = linkLocation;
Use Ajax to re-load only #content:
$( "#content" ).load(linkLocation, function(){
$('#content').fadeIn(500, function(){
// do something when the re-load is finished
});
});
You can't change the URL of the window via AJAX, but you could change window.location.hash. Others (in the comments) have mentioned using the history API.

Finding actual URL from <a href="#"

A page source snippet has the HTML:
Next
I know that the "#" is a placeholder that is handled by Javascript on the page. I believe the relevant Javascript snippet is:
function changepage(start) {
makerequest('/ajax/inventory_search.php', collectformvalues(start));
}
// do not flash the search options when using next/prev - just when the search is changed
function changepageforpagerlink(start) {
doEffectOnAjax = false;
changepage(start);
return false;
}
I need to know if there is a way that I can submit a URL and have the next page's page source returned. Is there a URL that is submitted at all in the above example?
My environment is VBA. I'm not using a browser, just communicating with the server. One thing I thought of is to mimic the "makerequest" function, but I don't know how to do that or if would even work. I know at the heart it's all just sending text to the server and receiving text back so I would think there is a way. . .
Bottom line is that I need to access the page source from the next page via VBA and not using a browser.
you can use JQuery to achieve this:
function changepage(start) {
makerequest('/ajax/inventory_search.php', collectformvalues(start));
}
changes to
function changepage(start) {
$.ajax({
type:POST,
url:"/ajax/inventory_search.php",
}).done(function(){
//do anything when it's done.
});
}

Categories

Resources