Change url with ajax call - php

I'm doing cross-domain GET to get cnn html like this:
$(function(){
var site = 'http://cnn.com';
$.get('proxy.php', { site:site }, function(data){
$(data).appendTo('#div');
}, 'html');
});
Im getting everything that I need except the url's sometimes are not complete urls but point to a certain path on there server like this:
/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3
So the problem is that if someone is clicking the link on my site the url will look like this:
http://MY-WEBSITE/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3
How can I get rid of my own url being inserted and replace it with 'cnn.com'?
I tried jquery split and replace but it doesn't work:
href = $(this).prop('href');
url = href.split('/');
href.replace(url[2], 'cnn.com');
I usually get an error in console 'split is not defined', when I fixed it the error moves on to 'url is not defined' and so on. Sometimes (with other code variations) I get no errors but it still doesn't work. I cant figure it out.

Looking at your code I am assuming you are using jQuery.
The problem is occurring because the source code on cnn.com seems to be using relative links. You can insert cnn.com at the beginning with the following jQuery
$(function() {
$('a').each(function() {
if ($(this).attr('href').indexOf('http') === 0) {
$(this).attr('href', 'http://www.cnn.com' + this.href);
}
});
});

You can simply check if the url is relative or not. Easiest way to do this is to check if it starts with http://.
var url = $(this).prop('href');
if (!(/^http/).test(url))
{
url = site + url; // prepend "http://cnn.com" to the address
}
alert(url); // url is now a full url
if you want a more generalised solution, you can use the regexp object on the site to determine if the prefix is there.
var site = "http://cnn.com";
var siteRegex = new RegExp("^" + site); // Regex - Starts with site
var url = $(this).prop('href');
if (!siteRegex.test(url))
{
url = site + url;
}
alert(url);

This little function can be used in a general purpose:
function RelativeToAbsoluteURL(root, url) {
var httpMatch = /https?:\/\//ig;
if (!httpMatch.test(url)) {
return root + (url.substr(0, 1) != "/" ? "/" + url : url);
} else {
return url;
}
}
Use:
RelativeToAbsoluteURL("http://www.cnn.com", "http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3");
RelativeToAbsoluteURL("http://www.cnn.com", "/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3");
Both will output the same URL (http://www.cnn.com/2013/01/24/business/samsung-record-fourth-quarter-2012-profits/index.html?hpt=hp_t3)

DEMO
Either seems to work:
var href = $(this).attr('href');
var url = (href.indexOf("/")===0) ? "http://...."+href:href;
Possible alternative - this one will return the fully qualified URL from the href
var href = this.href; // actual href and not the property
var url =(href.indexOf(location.hostname)===7) ? href.replace(location.hostname,"www.cnn.com"):href;
Using prop
var href = $(this).prop('href');
var url = (href.indexOf("/")===0) ? "http://...."+href:href;

Related

How to change html anchor tag query string

It is known that URL with querystring parameter can be rewritten with .htaccess. For example
localhost/mynews/category.php?cat=news&subcat=9
To
localhost/mynews/news/9
But is there any way to customize anchor tag
which is shown in bottom left corner while hovering link.
localhost/mynews/category.php?cat=news&subcat=9
to
localhost/mynews/news/9
PHP, jquery/javascript or htaccess, any way can we customize ?
On hover you can get your anchor href get querystring value rebuild url and set new url using attr in anchor tag.
var link = '';
$("a").hover(function() {
link = $(this).attr('href');
var var1 = $.urlParam('cat', link);
var var2 = $.urlParam('subcat', link);
var url = link.split('?')[0] + '/' + var1 + '/' + var2;
$(this).attr('href', url);
}, function() {
$(this).attr('href', link);
});
$.urlParam = function(name, link) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(link);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hover Me
Note: I take urlParam function from https://stackoverflow.com/a/25359264/965146 and slightly modified it. Rest code are mine.You must reset your url when anchor click may be routing didn't get your new url

Open external links in WordPress in an iFrame

I want to open all external links in an iframe like digg/themeforest.net
Most post on my site redirects users to external links and hence I want to use this method. I have searched a lot but couldn't find the answer I was looking for. Please help me get this done.
Thank you.
The solution I am looking for is
Question
When the link is clicked, if it is external it loads in iFrame
Supposing your iframe has id your-iframe
var $iframeSelector = $("#your-iframe");
var currentDomain = document.location.protocol + '//' + document.location.hostname;
var outboundLinks = 'a[href^="http"]:not([href*="' + currentDomain + '"])';
$(document).on('click', outboundLinks, function(){
$iframeSelector.attr('src', $(this).attr('href'))
});
Just add this to any javascript after DOM is loaded (in $(document).ready(function(){... }) block)
First you need to check if your anchor's href is external or internal, if it is external then load it in iframe
var comp = new RegExp( "your_site_url" );
var http_regez = new RegExp( "http" ); // for http:// and https://
var www_regez = new RegExp( "www" );
jQuery('a').click(function(event){
var href_val = jQuery(this).attr('href');
var is_external = false;
if(comp.test(href_val)){
is_external=false;
}
else if( http_regez.test(href_val) || www_regez.test(href_val) ){
is_external=true;
}
else{
is_external=false;
}
if(is_external){
event.preventDefault();
jQuery("#externalLinkIframe").attr('src',href_val);
return false;
}
});

A way to get a parameter from the URL

I have this issue i'm trying to solve.
I have this page lista.php
In which i load another page (which refreshes every x seconds) named pagination.php
I use this script:
function LoadContent()
{
$('#lista').load('pagination.php');
}
$(document).ready(function(){
LoadContent(); //load contentent when page loads
setInterval('LoadContent()',30000); //schedule refresh
});
Well, there is this URL:
lista.php?id=3
I need the pagination.php to grab the id, but it won't work..
the pagination.php is inside lista.php... how can i solve it?
I tried the GET method..
Any suggestion please?
Thanks.
To obtain id from your url like lista.php?id=3 you could use
var url = window.location.href;
var queryStr = url.substring(url.indexOf("?")+1);
var id = queryStr.split('=')[1];
So the whole code maybe like:
function LoadContent()
{
var url = window.location.href;
var queryStr = url.substring(url.indexOf("?")+1);
var id = queryStr.split('=')[1];
$('#lista').load('pagination.php?id=' + id);
}
$(document).ready(function(){
LoadContent(); //load contentent when page loads
setInterval('LoadContent()',30000); //schedule refresh
});
Add the parameter to the url, e.g.:
function LoadContent()
{
var id = ... <== assign id here
$('#lista').load('pagination.php?id=' + id);
}
$(document).ready(function(){
LoadContent(); //load contentent when page loads
setInterval('LoadContent()',30000); //schedule refresh
});
If you're using AJAX to load dynamically then that's a different URL, so append the current query string to the request with something like location.search.substring(url.indexOf("?")).
$('#lista').load('pagination.php' + location.search.substring(url.indexOf("?")));
i think you can use this:
$('#lista').load('pagination.php?id=<?php echo $_GET['id'] ?>');

include path and ajax not working?

I couldn't get "castMyVote" function to execute. It worked when I cast a vote in poll.php but not in index.php. I have ensure all php and js are in correct path. I tried another function "displayvotewithoutvote" in Index.php, I could display statistic without vote.
index.php:
include('poll.php');
poll.php:
<img src="images/vote_button.gif">
ajax.js:
function castMyVote(pollId,formObj)
{
var elements = formObj.elements['vote[' + pollId + ']'];
var optionId = false;
**for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionId = elements[no].value;
}**
Poller_Set_Cookie('dhtmlgoodies_poller_' + pollId,'1',6000000);
if(optionId){
var ajaxIndex = ajaxObjects.length;
ajaxObjects[ajaxIndex] = new sack(); //an api from simple ajax code kit
ajaxObjects[ajaxIndex].requestFile = serverSideFile + '?pollId=' + pollId + '&optionId=' + optionId;
prepareForPollResults(pollId);
ajaxObjects[ajaxIndex].onCompletion = function(){ showVoteResults(pollId,ajaxIndex); }; // Specify function that will be executed after file has been found
ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
Update: in ajax.js as showing above, it doesn't response after I include alert after, I afraid something wrong here:
for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionId = elements[no].value;
}
Please try this code in your poll.php
<img src="images/vote_button.gif" onclick="castMyVote(<?php echo $pollerId;?>,document.forms[0])">
This may help you.
Thanks,
Kanji
are you getting the pollid in the js?
var pollid="";
onclick="castMyVotepollid,....
try this

jQuery: Click tracking with PHP

Yes, I KNOW about Google Analytics. We use it for our overall site metrics, and I know we can track individual links. However, we needed a tracking solution for very specific links and we need that tracking data available to our web application in real time, so I wrote my own solution:
jQuery:
$.fn.track = function () {
var source, url, name, ref, $this;
$this = $(this);
if (window.location.search.substring(1) != '') {
source = window.location.pathname + "?" + window.location.search.substring(1);
} else {
source = window.location.pathname;
}
url = jQuery.URLEncode($this.attr('href'));
name = $this.attr('name');
ref = jQuery.URLEncode(source);
$this.live('click', function (click) {
click.preventDefault();
$.post('/lib/track.php', {
url: url,
name: name,
ref: ref
}, function () { window.location = $this.attr('href'); });
});
};
... using the jQuery URLEncode plugin (http://www.digitalbart.com/jquery-and-urlencode/).
Now, this code works fine with my PHP backend and on my machine, but it doesn't seem to work reliably for everyone else. Sometimes the parameters passed in via jQuery are NOT passed in, resulting in a record in the database with no name, url or ref.
For the life of me, I can't figure out why this might be happening; I know the $.post is triggering, since there are records in the database (in the PHP, I also record the IP of the request along with the timestamp), but in many cases the PHP script is receiving blank $_POST variables from jQuery.
I've tested it live on every browser I have access to at my workplace, and all of them work fine for me; however, about 75% of all the records created (not by my computers) come through as blank (most of them are using the same browsers I am).
Why could this be happening?
I think, in the end, my problem ended up being that it was taking too long for the request to be parsed by jQuery, and I'm pretty adamant about not wanting to make the links "dependent" on javascript (either that they wouldn't work without it or that the user would have to wait for the tracking request to complete before they hit the new page).
After browsing many other solutions online--borrowing from some and being inspired by others--I arrived at the solution below in native javascript:
if (document.getElementsByClassName === undefined) { // get elements by class name, adjusted for IE's incompetence
document.getElementsByClassName = function(className) {
var hasClassName, allElements, results, element;
hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
allElements = document.getElementsByTagName("*");
results = [];
for (var i = 0; (element = allElements[i]) !== null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)) {
results.push(element);
}
}
return results;
};
}
function addTracker(obj, type, fn) { // adds a tracker to the page, like $('xxx').event
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.addEventListener) {
obj['e' + type + fn] = fn;
obj[type + fn] = function() {
obj['e' + type + fn]( window.event );
};
obj.attachEvent('on' + type, obj[type + fn]);
}
}
function save_click(passed_object) { // this function records a click
var now, then, path, encoded, to, from, name, img;
now = new Date();
path = '/lib/click.php';
from = (window.decode) ? window.decodeURI(document.URL) : document.URL;
to = (window.decodeURI) ? window.decodeURI(passed_object.href) : passed_object.href;
name = (passed_object.name && passed_object.name != '') ? passed_object.name : '[No Name]';
// timestamp the path!
path += '?timestamp=' + now.getTime();
path += '&to=' + escape(to) + '&from=' + escape(from) + '&name=' + name; // compile the path with the recorded information
img = new Image();
img.src = path; // when we call the image, we poll the php page; genius!
while (now.getTime() < then) {
now = new Date(); // resets the timer for subsequent clicks
}
}
function get_targeted_links(target) { // finds targeted elements and wires them up with an event handler
var links, link;
if (document.getElementsByClassName) {
links = document.getElementsByClassName(target);
for (var i = 0; i < links.length; i++) {
link = links[i];
if (link.href) {
addTracker(links[i], 'mousedown', save_click(links[i]));
}
}
}
}
addTracker(window, 'load', get_targeted_links('trackit'));
... which seems to be much snappier than the jQuery plugin I had written above, and so far has been fast enough to track all the requests I've thrown at it.
Hope that helps someone else!
These "clicks" might be coming from bots, or someone with JS disabled. If you the links clicked must be tracked why don't you consider JS only links, ie. put URL in a different attr other than href, then use your click handler to process it, add referral check in your track.php
Also have you checked if all elements are links?

Categories