Add string to url on page load with jQuery? - javascript

I'm trying to add this specific string to the end of my url on page load:
?aa_campaign=f45632
(http://examplesite.com/test.html)
It's for marketing and tracking.
I've tried this:
if window.location.href.indexOf("http://examplesite.com/test.html") {
window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}
That straight up didn't work but the idea is what I'm looking for. Any thoughts?

No need for jQuery, you can do this with pure JavaScript in most "modern" browsers, i.e.:
if (window.location.href === "http://examplesite.com/test.html") {
window.history.pushState("object or string", "Title", "http://examplesite.com/test.html?aa_campaign=f45632");
}
The pushState() method
pushState() takes three parameters: a state object, a title (which is
currently ignored), and (optionally) a URL. Let's examine each of
these three parameters in more detail:
state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever
the user navigates to the new state, a popstate event is fired, and
the state property of the event contains a copy of the history entry's
state object.
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored
after the user restarts the browser, we impose a size limit of 640k
characters on the serialized representation of a state object. If you
pass a state object whose serialized representation is larger than
this to pushState(), the method will throw an exception. If you need
more space than this, you're encouraged to use sessionStorage and/or
localStorage.
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe
against future changes to the method. Alternatively, you could pass a
short title for the state to which you're moving.
URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to
pushState(), but it might attempt to load the URL later, for instance
after the user restarts the browser. The new URL does not need to be
absolute; if it's relative, it's resolved relative to the current URL.
The new URL must be of the same origin as the current URL; otherwise,
pushState() will throw an exception. This parameter is optional; if it
isn't specified, it's set to the document's current URL.
SRC : https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

You can add the string to window.location.search instead, for a more general solution.
if (location.origin + location.pathname === 'your url here') {
location.search += 'additional data here';
}
The advantage of this approach is that you can apply this code to multiple pages with less changes to the same code.
Note that this will cause a page reload, which might not be optimal to user experience. Since you said you are doing this for tracking, you can instead ping the page by appending an image with the new url to DOM. Something like this:
var pinger = new Image(0,0); // keep the size of the image 0
pinger.src = 'changed url here, with the new query param appended';
document.body.appendChild(pinger); // ping sent
pinger.parentNode.removeChild(pinger); // remove the node when ping is sent
Hope that helps :)

This version will preserve any existing query string, and properly append your "aa_campaign=f45632" parameter string.
var w = window.location;
if (w.search.indexOf("aa_campaign") == -1) {
window.location = w + (w.search.indexOf("?") == -1 ? "?" : "&") + "aa_campaign=f45632";
}
Example:
http://example.com --> http://example.com?aa_campaign=f45632
http://example.com/page.html?id=1 --> http://example.com/page.html?id=1&aa_campaign=f45632

try this:
if (window.location.href.indexOf("http://examplesite.com/test.html" !== -1) {
window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}

Related

I am using window.location.replace take time to render the reponse?

The actual scenario is like I have 6k table rows which coming after the new action call. Below is call
var url = parent.getActionURL('fullExpand') + '?object=' + getTableBeanName();
if (typeof levels !== 'undefined') {
url += '&expandTo=' + levels;
}
window.location.replace(url);
The reponse is coming from server but it is not rendering in ui if we touch any dom element then reponse is rendering.if we change window.location.replace to window.location.href = url. Then problem get resolved for first time the behaviour is not consistent
The question is not totally clear, but they both navigate to the URL. replace() replaces the current document and it doesn't add a record to history, the behavior should be consistent in both cases.
With replace(), when the user clicks the back button they are returned to the page before the page that they were redirected from, this might cause your confusion. (read here)
You should use what is best for your use case.

Can i pass information through the URL when i am using jQuery Mobile?

I have a mobile application that opens an in-app browser that uses the URL to pass information to my server , like the deviceID.
For example the browser will open the web-page (jquery Mobile) : www.myserver.com/doWork.html#deviceID
On the server part using JavaScript inside the doWork.html file, I get the deviceID like this:
var userId = window.location.hash.substring(1);
Is it ok that i pass information using the hash # ? In jquery mobile the hash # is used to change between pages when someone uses the Multi-Page template structure . So i am afraid that maybe i should use something else , like a question mark (?) ?
Or its perfectly fine ?
NO. Stop using # for your data transfers. Let jQM do its thing. Don't disturb it. Use Query strings( adding ? in url). My advice is to stop using query strings (? tags) and # tags to send data to the next page. Handle it using localStorage. Its more secure compared to Query strings because the user wont see the URL change, so your sensitive data is hidden, at least to a little extent. localStorage is HTML5's API which is like a temporary storage set aside per domain. This data will persist until data is cleared in cache. Assuming you have an anchor tag which goes to dowork.html,
Go to Do work
Add an attribute for device ID in the tag itself, like this :
Go to Do work
You'd be doing this dynamically you might also use it the same way. You get the gist right?
A click event for this would look like this :
$(document).on("click", "a", function(e) //use a class or ID for this instead of just "a"
//prevent default
e.preventDefault();
//get device id from tag attribute
var deviceId = $(this).data("deviceid");
//set it in localStorage
localStorage["dId"] = deviceId;
//redirect
$.mobile.changePage(this.href);
});
Then, in the other page's pageinit (or any event), get the device id from storage and send the ajax call to the server.
//assuming #dowork is the id of a div with data-role="page"
$(document).on("pageinit", "#dowork", function() {
//get from storage
var deviceId = localStorage["dId"];
//make ajax call or server call with deviceId here
});
But, if you still want to use URL for this, look at this question. I've given a decent enough answer over there.
To pass variables to the server you should avoid using the # symbol because regardless of the framework you are using this symbol is used for other purposes, to pass info to the server in a GET request you should use the ? symbol, something like this should do it: www.myserver.com/doWork.html?deviceID=1233455

How to correctly read Javascript hash in custom affiliate URL?

I'm creating a custom affiliate program. I want my links to be as SEO friendly as possible, so I will use a Javascript hash appended to the URL to send the affiliate id, read the affiliate id, store the click, and then 301 re-direct to the page they were linked too. That way we have no canonical issues whatsoever, and every affiliate link passes link juice!
Now, how would I read the following URL?
www.mydomain.com/seo-friendly-url#ref=john
After getting the hash value for ref and adding the click, how would I then 301 re-direct the user back to
www.mydomain.com/seo-friendly-url
Any help is greatly appreciated!
Fragment identifiers (the part after the #) are not sent to the server, so they cannot be read by anything that could then emit an HTTP response (which you need for a 301 redirect).
The "hash" portion of a URL is not passed to the server, so you will not be able to utilize this data for any server-side redirection or processing directly. However, it is possible to grab the hash on page load and pass it on to the server via AJAX or redirection:
To immediately redirect a user from www.mydomain.com/seo-friendly-url#ref=john to www.mydomain.com/seo-friendly-url/ref/john
if (window.location.hash.match(/#ref=/))
window.location = window.location.href.replace('#ref=', '/ref/')
... but then, why not have just used www.mydomain.com/seo-friendly-url/ref/john to begin with and save the extra leg work? The other route, through AJAX, involves reading the value of the hash after the page has loaded and sending that off to the server to be recorded.
(note: this code uses a generic cross-browser XMLHTTPRequest to send an AJAX GET request. replace with your library's implementation [if you are using a library])
window.onload = function () {
// grab the hash (if any)
var affiliate_id = window.location.hash;
// make sure there is a hash, and that it starts with "#ref="
if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
// clear the hash (it is not relevant to the user)
window.location.hash = '';
// initialize an XMLRequest, send the data to affiliate.php
var oXMLHttpRequest = new XMLHttpRequest;
oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
oXMLHttpRequest.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
// do anything else that needs to be done after recording affiliate
}
}
oXMLHttpRequest.send(null);
}
}

Passing Data from Parent Window of One domain to Child window of another domian

I have two domains say X and Y, both are on different server with different IPs.
Now the case is that on one page of domain X there is a Link which opens the pop-up of domain Y.
User searches for some data on that popup and then clicks on "Done"
On click the values related to the searched field should be passed to a page on domain X.
I am using PHP, HTML, and js for this.
P.S.: The thing works when the domain name is same but I want the solution where domain names and server are different.
I just want to add that it is possible to pass data from a window with one domain to a window with another domain via the window.name property. Of course, this property wasn't intended for that purpose, and language purists are going to hate me for this. Nonetheless, this is how it's done, quick and dirty:
On Domain X:
var PREFIX = "your prefix here";
// The second parameter of window.open() sets window.name of the child window.
// Encode JSON and prepend prefix.
window.open("http://domain-y.example.com/", PREFIX + JSON.stringify({"foo":"bar", "abc":123}));
On Domain Y:
var PREFIX = "your prefix here";
if(window.name.substr(0, PREFIX.length) == PREFIX){
// Remove prefix and decode JSON
var data = JSON.parse(window.name.substring(PREFIX.length));
// Do what you need to do with the data here.
alert(data.foo); // Should alert "bar"
}
The PREFIX is optional, but I prefer to include it in case Domain Y is accessed by some other page that sets the window.name property. Also note that you're not required to use JSON (and that you shouldn't if you're dealing with dinosaur browsers), but I like JSON because I can pass more than one property in an object.
EDIT: If you need Domain Y to pass data back to Domain X, you can have Domain Y save data in window.name and navigate to a passer page on Domain X, which can easily pass data to the original window. Try this:
On Domain Y:
// Somewhere earlier in the code:
var PREFIX = "your prefix here";
// Call this function when the Done button is clicked.
function passDataBack(data){
window.name = PREFIX + JSON.stringify(data);
window.location = "http://www.domain-x.com/passer.html";
}
On http://www.domain-x.com/passer.html:
// Somewhere earlier in the code:
var PREFIX = "your prefix here";
if(window.name.substr(0, PREFIX.length) == PREFIX){
// Remove prefix and decode JSON
var data = JSON.parse(window.name.substring(PREFIX.length));
// Send data to parent window
window.opener.processData(data);
}
In the original page, there should be a function called processData that takes the data and does something with it.
You need to investigate
CORS (for older IEs you will need XDR) or
window messaging or
JSONP or
send the variables via the url
I know this is an old question but I think this may be a more appropriate answer to the question
You should add the following code to the http://domain-x.com
window.addEventListener("message", function(event) {
console.log(event.data); // {user: 'data'}
}, false);
... at the http://domain-y.com
userClicksDone() {
try {
// This may throw an error in case of people access
// http://domain-y.com directly, not via popup from
// http://domain-x.com
//
window.opener.postMessage({user: 'data'}, 'http://domain-x.com');
} catch(e) { }
// Closes this popup
//
window.close();
}
More info at Mozilla.
Credits to #mplungjan

Make an ajax request to get some data, then redirect to a new page, passing the returned data

I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.

Categories