How to get URLs from referring page in jQuery - javascript

I need to get URLs from my referring page via jQuery. The URLs are inside an <a> element that looks like this in HTML:
<a href="http://localhost/sr19repairables/vehicles/repairables/2011-chrysler-town-country-touring-minivan-4d/" title="2011 Chrysler Town & Country Touring Minivan 4D">
There are multiple <a> elements on the referring page and I need to get the URLs from all of them and put them in an array. Any help?
I have a button on my second page with this jQuery attached to it:
$(document).ready(function(){
$(".single_vehicle_previous_button").click(function(){
var referrer = document.referrer;
if (document.referrer == "http://localhost/sr19repairables/vehicles/rebuilt-vehicles") {
alert(value=referrer);
};
if (document.referrer == "http://localhost/sr19repairables/vehicles/repairables/") {
alert(value=referrer);
};
if (document.referrer == "http://localhost/sr19repairables/vehicles/") {
alert(value=referrer);
};
});
});
So if my referring page is one of these three, I want it to get the URLs in the anchors on those pages. The alert is just for testing purposes. Does that help clear things up?

If you already know it's on the same site (as you've checked the url), then you shouldn't have the usual problems with loading random pages via ajax.
You can use $.ajax to get the page, then jquery to parse the html returned:
$.ajax(document.referrer)
.done(function(html) {
var urls = $("<div/>").html(html)
.find("a")
.map(function(i, e) { return $(this).attr("href"); }
});

Related

Refresh page with data from $.post()

I am trying to send data to a index page when a link on that page is clicked. the index.php page looks like this:
include "../app/bootstrap.php";
include ("../src/controllers/DisplayContentsController.php");
$data = new DisplayContentsController();
$link = (isset($_POST['link']) ? $_POST['link'] : null);
if ($link != null)
{
$data->show($twig, $starting_file_path . '/' . $link);
$starting_file_path = $starting_file_path . '/' . $link;
}
else
{
$data->show($twig, $starting_file_path);
}
and on the Twig template that is loaded I have this:
<script>
jQuery('.show_content').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery.post(window.location, { link: href });
});
</script>
I want to reload the page with the new link that way it loads the correct directory. But when I do the jQuery.post() the content that is displayed does not change. Can someone help my find out what is going wrong and how I can accomplish this?
The output from the POST request would be returned on the success handler function. For example, you would need to do something like this:
jQuery('.show_content').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery.post(window.location, { link: href } , function(data){
//data will have the new HTML after the page posted back. You can use that
//HTML to load if onto an element on the page. Something like:
$('#content_result').html(data);
});
});
Assuming you have a div with "id = content_result" -or something like that- that you can use to load the HTML into it.
If you want to append the result to the existing HTML already displayed inside #content_result then simply do:
$('#content_result').html($('#content_result').html()+data);
Now, keep in mind that this will return everything - the full page - and if you blindly keep appending things, you'll end up with a page that does not conform to valid HTML -for example, a page with more than 1 <head>,<body> sections, etc. The best thing to do is to extract the section that you really care about, and append only that section such that you always end up with a valid HTML document.
jQuery offers plenty of options to do this sort of thing.

Click all links on page containing string?

I'm trying to add a function to a toolbar Chrome extension I've made. What I'd like it to do is once a navigate to a particular page I'd like be able to push a button on the tool bar and have it "click" all of the links on that page containing harvest.game?user=123456 with 123456 being a different number for all of the links. It could be using jquery or javascript. The only catch is that the script will need to be inserted as an element to the head of the page as cross domain scripting is not allowed so no external references to a js file. I can handle the adding of the element but, I'm having no luck figuring out the actual function.
The elements containing the links all look like this:
<div class="friendWrap linkPanel">
<h5>Christine...</h5>
<div class="friend-icon">
<img src="https://graph.facebook.com/100001726475148/picture"></div>
<div class="levelBlock friend-info">
<p>level</p>
<h3 class="level">8</h3></div>
Harvest
<a class="boxLink" href="profile.game?user_id=701240"><span></span></a></div>
Something like this (I know this is a mess and doesn't work)? OR maybe something BETTER using jquery?
var rlr=1;
function harvestall(){var frt,rm,r,rld,tag,rl;
var frt=1000;
r=document.getElementsByClassName("friendWrap linkPanel");
rl=r.length;
rld=rl-rlr;
if(rld>=0){tag=r[rld].getElementsByTagName('a');
if (rl>=1 {rlr++;harvestall();}
else if (rl>=1) {tag[1].onclick();do something??? ;}
}
Something like this should work
$("a[href*='harvest.game?user=']").trigger("click");
// Using jQuery, wait for DOMReady ...
$(function harvestLinks() {
// Only create regexp once ...
var reURL = /harvest.game\?user=/,
// Create a ref variable for harvest links ...
// Use 'links' later without querying the DOM again.
links = $("a").filter(
function() {
// Only click on links matching the harvest URL ...
return this.href && reURL.test(this.href);
}
).click();
});

Javascript substring method assistance

So long story short im working on a web app and using AJAX within it.
I'm trying to disable the default actions of links when clicked, attach a hash value to the link and then remove the "#" from the url.
the problem im having is that, although the hash values are being attached accordingly, the substring method isnt extracting the "#", it extracts the letter after it.....
here is my code. PS, i left my comments inthere so you get where im trying to go with this
so i dont know....my logic or setup may be wrong....
$(document).ready(function(){
//app vars
var mainHash = "index";
var menuBtn = $('.leftButton');
//~~~~~~load the index page at first go.
loadPage();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~menu show/hide
menuBtn.click( function(){
$('#menu').toggleClass();
});
//Menu items on click , disable link default actions.
$('#menu a').click( hijackLinks );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~functions for mobile index load AND hijacking app links to AJAX links.
function loadPage(url){
if( url == undefined){
$('#contentHere').load('index.html #content', hijackLinks);
window.location.hash = mainHash;
} else {
$('#contentHere').load(url + '#content', hijackLinks );
}
}
function hijackLinks(e){
var url = e.target.href;
e.preventDefault();
loadPage(e.target.href);
window.location.hash = $(this).attr("href").substring(1);
}
});
what im wanting is to remove the "#" from the url. What am i doing wrong, what am i not seeing/understanding?
ive tried substring/substr etc and both do the same thing in that no matter what numbers i choose to insert into the substrings params, they remove EVERYTHING BUT the "#" lol....
Thanks in advanced.
Well, you don't really change the link itself, you only change the window.location.hash, and the hash always has a "#" at the beginning.
What you need to do in order to change the entire url (and remove the '#') is to manipulate the browser history.
Although you should know it works only in newer browsers (the exact browser versions are in the link), so if you target your website to older too browsers you might need to think about having a fallback using the hash. If you decide to have such a fallback, I suggest searching for a plugin which does it instead of making it all yourself.

Load javascript in html within content pane

I have an html file that I want to be loaded from various pages into a dijit.contentpane. The content loads fine (I just set the href of the contentpane), but the problem is that javascript within the html file specified by href doesn't seem to be executed at a consistent time.
The final goal of this is to load an html file into a contentpane at an anchor point in the file (i.e. if you typed in index.html#tag in order to jump to a certain part of the file). I've tried a few different methods and can't seem to get anything to work.
What I've tried:
1.
(refering to the href of the dijit.contentpane)
href="page.htm#anchor"
2.
(again, refering to the href of the dijit.contentpane -- didn't really expect this to work, but decided to try anyways)
href="#anchor"
3. (with this last try inside the html specified by href)
<script type="text/javascript">
setTimeout("go_to_anchor();", 2000);
function go_to_anchor()
{
location.href = "#anchor";
}
</script>
This last try was the closest to working of all of them. After 2 seconds (I put the delay there to see if something in the dijit code was possibly loading at the same time as my javascript), I could see the browser briefly jump to the correct place in the html page, but then immediately go back to the top of the page.
Dojo uses hashes in the URL to allow bookmarking of pages loaded through ajax calls.
This is done through the dojo.hash api.
So... I think the best thing you can do is use it to trigger a callback that you write inside your main page.
For scrolling to a given position in your loaded contents, you can then use node.scrollIntoView().
For example, say you have a page with a ContentPane named "mainPane" in which you load an html fragment called "fragment.html", and your fragment contains 2 anchors like this :
-fragment.html :
Anchor 1
<p>some very long contents...</p>
Anchor 2
<p>some very long contents...</p>
Now say you have 2 buttons in the main page (named btn1 and btn2), which will be used to load your fragment and navigate to the proper anchor. You can then wire that up with the following javascript, in your main page :
<script type="text/javascript">
require(['dojo/on',
'dojo/hash',
'dojo/_base/connect',
'dijit/layout/BorderContainer',
'dijit/layout/ContentPane',
'dijit/form/Button'],
function(on, hash, connect){
dojo.ready(function(){
var contentPane = dijit.byId('mainPane');
var btn1 = dijit.byId('btn1');
var btn2 = dijit.byId('btn2');
btn1.on("Click", function(e){
if (!(contentPane.get('href') == 'fragment.html')) {
contentPane.set("href", "fragment.html");
}
hash("anchor1");
});
btn2.on("Click", function(e){
if (!(contentPane.get('href') == 'fragment.html')) {
contentPane.set("href", "fragment.html");
}
hash("anchor2");
});
// In case we have a hash in the URL on the first page load, load the fragment so we can navigate to the anchor.
hash() && contentPane.set("href", "fragment.html");
// This callback is what will perform the actual scroll to the anchor
var callback = function(){
var anchor = Array.pop(dojo.query('a[href="#' + hash() + '"]'));
anchor && anchor.scrollIntoView();
};
contentPane.on("DownloadEnd", function(e){
console.debug("fragment loaded");
// Call the callback the first time the fragment loads then subscribe to hashchange topic
callback();
connect.subscribe("/dojo/hashchange", null, callback);
});
}); // dojo.ready
}); // require
</script>
If the content you're loading contains javascript you should use dojox.layout.ContentPane.

Javascript - how do I minimise this code example?

a quick question.
At the moment I have 12 links on a page, and 12 corresponding javascript codes that run when a each button is clicked.
I know 100% there must be a method of having 1 javascript code and the link passing a variable to it, so I don't have to have 12 different codes.
EG. Here is a link I'm currently using:
Anatomical Pathology
And the Javascript function that is run when the link is clicked loads some html from a php script into a div which is previously defined as level2:
$('#button1').click(function() {
level2.load("http://hello/script.php?url=poodles");
});
What I'd really like to do is something like this with the link:
Anatomical Pathology
And the function something like this, so I only need the 1 function not 12:
$('#button1').click(function() {
level2.load("http://hello/script.php?url=' + passurl + '");
});
How do I go about getting the data from the link tag into javascript, and also how do I add this passed variable into the url I want the javascript to pull data in from?
passurl isn't standard attribute, you should use data-passurl
$('#button1').click(function() {
var passurl = $(this).data('passurl'); // or $(this).attr('data-passurl');
level2.load("http://hello/script.php?url=" + passurl);
});
Why don't you utilize your hash there...
Anatomical Pathology
In your script
$(".button").each(function() {
// get the hash and extract the part we want store it in this enclosure
var url = $(this).attr("href").replace(/^#\//, "");
// create a click handler that loads the url
$(this).click(function() {
level2.load("http://hello/script.php?url=" + url);
});
});
This also brings about the possibility to extrapolate from that so that a hash passed through the url can also operate the script loading...
You can use the rel attributte (or any data- attributes if your using HTML5 Doctype) to save your URL and add a class to the links you want to execute your callback.
Anatomical Pathology
Your Callback:
$('a.button').click(function() {
level2.load("http://hello/script.php?url=' + $(this).attr('rel') + '");
});
For a more extensible solution you could consider making a json structure for your urls:
var urls = [{
"poodle":{
"url":"http://hello/script.php?url=poodle",
"someOtherData":"data"
},
"otherDog":{
"url":"http://hello/script.php?url=otherDog",
"someOtherData":"data"
}
}];
You would store some sort of key somewhere in your HTML element:
Anatomical Pathology
Then you would leverage this data structure in your functional code:
$('a').click(function () {
var key = $(this).attr('rel');
level2.load(urls[key].url);
});
As per Stuie, add a class to the links so that you can target them all at once. However, I don't see the need to fool with the hash, and I wouldn't add a bunch of click events either. Just delegate once and you're done:
<div id="wrapper">
Poodles
Schnausers
</div>
and the JS:
$('#wrapper').delegate('a.button', 'click', function(e) {
e.preventDefault();
var passurl = $(this).attr("href");
level2.load("http://hello/script.php?url=" + passurl); // assuming "level2" is valid from elsewhere
});
Where I have "#wrapper" you would designate any unique selector that is an ancestor of all your links. It's an element that listens for clicks on the a.button elements within.

Categories