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

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

Related

How to execute some jQuery or JavaScript code after a redirect has completed

How can I execute jQuery/JS code as soon as a jQuery/JS redirect like...
$(location).attr('href','/target_path');
...or...
window.location.href = "/target_path";
...has finished loading the new page?
Specifically, I need to pass an alert message and insert it into and display it (enclosed in some HTML) on the new page.
You can't. Once the redirect happens you are no longer on that page. You can't execute code on a page you are no longer on. If you want the next page to do something then you need to pass, either by cookie or URL parameter, a flag that instructs it to do so.
It is impossible to tell JavaScript to execute some code after a redirect.
However you have different options:
Pass a string in the redirect URL and then do something on "ready"
Store some information in a cookie and then do something on "ready"
Store some data using DOM storage (namely sessionStorage) if you don't mind the smaller browser support
You can't do that in the page that's redirecting. You can read the referrer in the landing page (document.referrer), and then decide whether to display an alert based on that, though.
var x = "It's some text";
var loc = '/target_path';
loc += '?message=' + encodeURI(x);
The JS file on the new page can then look at the query string to see if a message is there, and do the required action if it's detected.
You can use window.location.search on the new page to see what's there, although I'd recommend hunting for a deparam function in a library to turn the query string into a more usable object.

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

How to get the title of a link using JavaScript

I want to get the title of a webpage without opening it, i.e. without using window.open().
I basically want to check whether the page i am providing the link for exists or an error is returned.
What I am trying is checking for similar links. Here is the code
(I want to know when to break out of this loop, i.e. at what point the link I am writing exists).
document.getElementById("TOI").innerHTML="<p>";
if (month<10) var m="0"+month;
else var m=month;
for(var i=1;;i++){
alert("ji");
var a="http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf";
alert(a);
var link=window.open(a);
window.focus();
alert(link.location);
alert(link.document.title);
if(link.document.title!="The page cannot be found"){
link.close();
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<a href='http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf' target=_blank>Page "+i+"</a> ";
}
else{link.close();break;}
}
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<\p>";
}
See to check if a url exists or not, you must use a server-side scripting language. Javascript is client-side and can't access server. So, first of all make a server side script (maybe php) that returns the status of url that you wanna check. Then from javascript side, use an ajax call to get the result of that script. That way you can check your url array, if all of them exists or not.
var attribute = element.getAttribute("title");
I want to get title of a webpage
without opening it(that is without
using window.open()) I basically want
to check whether the page i am
providing the link for exists or an
error is returned
Just because a page has a title doesn't mean it exists.
http://www.google.com/thispagedoesnotexist.htm
Examine HTTP status codes rather than page titles:
Can Prototype or JQuery return an HTTP status code on an AJAX request

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.

Modify url for bookmarking using JavaScript

I'm exploring my options for modifying urls in the browser bar for bookmarking purposes.
Ideally, I'd like to add querystring parameters and cannot determine if this is even possible. I don't want the page to refresh and want to add querystring values on link clicks, ajax calls, etc.
If I can't add querystring parameters, then I'd like to add hash values (http:://someurl.com#hash-value). How should I go about doing this? Should I use plain JavaScript or a framework (jquery, prototype, etc.) and/or framework plugin.
To modify the hash, you can simply do the following in plain JavaScript:
window.location.hash = 'hash-value';
It will add #hash-value to your URL, or will replace it if it already exists, without refreshing the page.
Then to check if a hash value is present, simply do the following:
if (window.location.hash) {
// Hash is present
// Use window.location.hash as required
}
else {
// No hash was set
}
If you modify the query string, it will refresh. So you should modify window.location.hash.

Categories