JQuery Using passed parameter value to initialize a page via $(document).ready - javascript

I am trying to access or make a parameter value which was passed via an <a> visible within another javascript file. I can't figure out how to go about it.
I have the ff. line of code which goes to a new page: student_learn_topiclink.php everytime the link is clicked
var topicLink = $('<a>' + topicTitle+ '</a>').addClass('topic_link').attr('href','view/student_learn_topiclink.php?topicId=' + topicId).attr('target','_blank');
This is what shows in the address bar after clicking the topicLink
http://localhost/cai/view/student_learn_topiclink.php?topicId=5
I want to use the value 5 in student_learn_topiclink page's JS file.
How can I expose or make the topicId = 5 visible in student_learn_topiclink JS file?
In student_learn_topiclink.js, I'd like to do something like this,
$(document).ready(function(){
alert(topicId);
});

See this thread about retrieving URL parameters with javascript. For your specific example, try the following:
var url_string = window.location.href;
var url = new URL(url_string);
var topicId = url.searchParams.get("topicId");
console.log(topicId);
Example fiddle: http://jsfiddle.net/craftman32/yxrvbcun/1/

You can use like this :
var topicId = window.location.search.split('topicId=')[1];
console.log(topicId);

Related

exchange variables between html files in javascript

I am trying to share variables between two html pages. I am only using javascript and HTML5 to develop a windows 8 app. Based on an image which a user clicks on one page, I want a div on a second page to be populated with that image. Any ideas?
When I click on the image, I am currently calling the following function:
function imageClick(url) {
//var id = parsed.ClientID;
//window.location= url + "?" + id
window.location = url;
}
Then in my html file, I have this line:
<img onclick="imageClick('pages/page2/page2.html')"
data-win-bind="src:image" style="width: 133px; height: 125.5px;">
I was thinking of getting that id in the next page's url (if I were to uncomment the commented lines above) but it's a bit hackky and I don't actually know how to go about executing the retrieval of that on the next page..
Is there a more efficient and easy way of doing this in javascript? Like an equivalent of sessions in php or something?
Javascript does not have session variables because it runs on the client side. You can use URL parameters and cookies in order to achieve the same results.
You can get the URL parameter by using this function:
http://ziemecki.net/content/javascript-parsing-url-parameters
Add the link to the image to the query part of the url when they click. Something like you had in the comment, assuming you don't have a query part already:
function imageClick(url) {
//var id = parsed.ClientID;
window.location= url + "?src=" + url.src;
//window.location = url;
}
The other page can use window.location.search to extract it, strip off the src=. The code would look something like this:
var src = window.location.search;
if (src.indexOf("src=") == 0) {
src = src.substring(4);
}
newPageImageElement.src = src;
Where newPageImageElement is the <img> where you want to display the picture on the second page.

Jquery extract string from url and load remote element

I'm new in Jquery, I would like to have Jquery code to get the current page url and if the url contains certain string then load remote element.
example:
i have the page urls like this:
"http://......./Country/AU/result-search-to-buy"
"http://......./Country/CA/result-search-to-buy"
"http://......./Country/UK/result-search-to-buy"
the part "/Country/AU" is what I need to determine which page element I should load in, then if "AU" I load from "/state-loader.html .state-AU", if "CA" I load from "/state-loader.html .state-CA"
I have a builtin module "{module_pageaddress}" to get the value of the current page url, I just dont know the Jquery logic to let it work.
I expect something like this:
if {module_pageaddress} contains "/Country/AU/"
$('#MyDiv').load('state-loader.html .state-AU');
if {module_pageaddress} contains "/Country/CA/"
$('#MyDiv').load('state-loader.html .state-CA');
You can try the following if the country string is always last before the last slash in the URL
See a live fiddle
var url = "http://......./Country/AU/result-search-to-buy"
var loc = url.split( '/' );
//should be using the next line in live
//var loc = window.location.pathname.split( '/' );
var country = alert(loc [loc.length-2]);

Javascript - reload page with different QueryString

I want to reload a page using JavaScript passing different parameters in URL.
My Page name is test1.aspx, I used:
window.location="test1.aspx?user=abc&place=xyz";
It's not working...!!!
window.location is an object. You need to access the href property on it, like this:
window.location.href="test1.aspx?user=abc&place=xyz";
If you need to send dynamic value, then
var user = "abc";
var place = "xyz";
window.location.href = "test1.aspx?user=" + user + "&place=" + place;
window.location = "path page?user=" + $("#txtuser").val();

Get current URL and modify subdirectory and then go to URL with Javascript

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders:
/en/
/chi/
What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.
But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
but it doesn't explain how to modify and go to the new link.
You help will be greatly appreciated!!
To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.
Here's a script that does this with JavaScript if that's what you decide you'd like to do.
<!DOCTYPE html>
<body>
Content before the link.
<script>
(function () {
// this assumes you're on the en version and want to switch to chi
var holder = document.createElement("div");
var url = window.location.href.replace("/en/", "/chi/");
var link = document.createElement("a");
link.innerText = "Chewa"; // or whatever the link should be
link.href = url;
holder.appendChild(link);
document.write(holder.innerHTML);
})();
</script>
Content after the link.
</body>
If you simply want to take the full URL and replace /en/ with /chi/ or vise-versa, use the code below.
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
Or, a bit more concise (un-commented version)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
Note: In JS, when you modify window.location.href, the new URL is automatically loaded.
Here's a working fiddle for you to play with.
It looks like you need to change the window.location.pathname. For example:
// assuming the url `http://www.example.org/en/foo/bar/page.html`
var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");
See:
https://developer.mozilla.org/en/DOM/window.location

Pass a Simple URL Variable into and Input Field via Javascript

I have found plenty of ways to do this via PHP but on a simple HTML site I have run into a roadblock. And I'm not really strong on JS so that doesn't help.
Basically I am passing a very simple URL variable (a ref #) via a link (...com/Apply-Online?12345) and I need to load it into an input text field on a form in the linked page. Most of the scripts I have found want to parse out multiple variables and it gets really complicated in a hurry. Since I only have 1 value it seems like there should be an easy way to parse the variable from the URL and pass it into a var and pass that to the ID of the field.
I have the window.onload part figured out. I just need the code to parse out the variable.
window.onload = function(){
document.getElementById("input_id").value = 12345;
};
It is as simple as:
document.getElementById("input_id").value = location.search.replace('?','');
Assuming your link includes a variable name, such as ...com/Apply-Online?var1=12345:
<script type="text/javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
window.onload = function(){
document.getElementById("input_id").value = $_GET('var1');
};
</script>
Source: http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
var value = document.location.search;

Categories

Resources