heisenberg
heisenberg

Reputation: 1954

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

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

});

Upvotes: 1

Views: 94

Answers (2)

Younes Zaidi
Younes Zaidi

Reputation: 1190

You can use like this :

var topicId = window.location.search.split('topicId=')[1];
console.log(topicId);

Upvotes: 0

Michael Hurley
Michael Hurley

Reputation: 369

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/

Upvotes: 1

Related Questions