how to get url variable using jquery/javascript? - javascript

I would like to get URL request variables from a link and pass them to a CFC component. I already have working code (jQuery, AJAX, CFC) that will handle everything, but I just need to grab #URL.whatever# from a particular link.
Within Coldfusion code I can easily do so with #URL.whatever# but have no idea how to get it from the client side. Also, does it matter if I have been using IIS URL rewrite? I am currently rewriting www.website.com/page.cfm?category=cat1 to www.website.com/page/cat1.
in both cases Coldfusion can access the request variable with #URL.category#, there is absolutely no difference. So how can I do this with JavaScript/jQuery, it shouldn't be complicated, right?

Well, we'll need more details to suggest how to get a reference to the link, but something like this should work:
HTML
<a id="mylink" href="www.website.com/page.cfm?category=cat1">Website.com</a>
JS
var href = document.getElementById( 'mylink' ).href;

This question proposes a method to get the variables, I find it slightly easier to understand than Blaise's regular expression. It also properly unencodes values from the URL Get Querystring with Dojo
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
var params = getUrlParams();
console.log(params.myParam);

Right, what you want to use is function to parse the window.location.href variable.
var URL_PARAM = getUrlVars()["category"];
Or, if the URL to your page was www.website.com/page.cfm?category=cat1&anotherparam=12345
var URL_PARAM1 = getUrlVars()["category"];
var URL_PARAM2 = getUrlVars()["anotherparam"];
I can't say for sure how it would operate with URL rewrites.
URLVars:
function getUrlVars() {
var vars = {};
var parts =window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[ decodeURIComponent(key)] = decodeURIComponent(value);
});
return vars;
}

Related

Is there a way to call a specific javascript function in a single js file for a specific page URL?

I have a question, i wanted to know if there is a way to call a specific function if a specific page URL is opened?
#shop_modal is in http://myurl/liste-boutique.php
#dep_modal is in http://myurl/index.php
Right now, i have Error when i try to open the #dep_modal because JS cant find #shop_modal on that page same page, so it does not execute below that.
I think AJAX can help figuring this out, otherwise i will have to split the code in 2 JS files, which i don't want to
const new_shop = $("#new_shop")[0];
const save_shop = $("#shop_form")[0];
const close_shop_modal = $("#close_shop_modal")[0];
const new_departement = $("#new_dep")[0];
const save_departement = $("#dep_form")[0];
const close_dep_modal = $("#close_dep_modal")[0];
// I want this to be called if the URL is http://my-URL/liste-boutique.php
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
// I want this to be called if the URL is http://my-URL/index.php
new_departement.addEventListener('click', function(){
$("#dep_modal")[0].style.visibility = "visible";
})
i need to ask question, but i don't know what to change here
Thanks again !!
You can check window.location.href. E.g.
if (window.location.href === 'http://my-URL/liste-boutique.php') {
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
});
}
Instead of checking the url, check if the element you want to find is on the page:
var $new_shop = $("#new_shop");
if ($new_shop.length > 0) {
var new_shop = $new_shop[0];
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
}
(I've used $ prefix on $new_shop to show it's a jquery object just for clarity)
Or, using your code as-is:
var new_shop = $("#new_shop")[0];
if (new_shop != undefined) {
new_shop.addEventListener...
Alternatively, if you use jquery, you don't need to worry about it as it will automatically not apply if the element doesn't exist:
$("#new_shop").click(() => { $("#shop_modal)").fadeIn(); });

How i can write value btag to another resource in Local Storage

For example,this my resource :
http://lands.dev/ml/sport-email/de/01-ronaldo/index.min.html?btag=a_1064b_333c_
On this web page i have a link, after click we redirect to another web page.
How can i read this value 'btag=a_1064b_333c_' from my url and write to Local Storage another resource after clicking.
Thank you so much for help.
The URLSearchParams interface defines utility methods to work with the query string of a URL.
Example:
var paramsString = "btag=a_1064b_333c_"
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
searchParams.has("btag") === true; // true
searchParams.get("btag") === "a_1064b_333c_"; // true
searchParams.getAll("btag"); // ["a_1064b_333c_"]
It's pretty new but it is a part of ES standard and very simple.
Polyfill:
https://github.com/WebReflection/url-search-params
Try this javascript code.
var urlPart = window.location.search.substr(1);
var val = urlPart.split("=")[1];
window.localStorage.setItem('btag', val);

Passing parameters to IFRAME in Dynamics CRM using javascript

I've following code snippet to access http://localhost:80/testsite in IFRAME. It worked fine but as soon as I went to pass the fields value as parameter nothing get happen. I tried directly access the page from browser with parameters so page is behaving fine. I cannot figure out the things after spending a lot of time. I would like to seek your kind patience on this basic question.
code Snippet
function forwardValues(){
var ordername = Xrm.Page.getAttribute("name").getValue();
var IFrame = Xrm.Page.ui.controls.get("IFRAME_sendvalue");
var Url = IFrame.getSrc();
var params = Url.substr(Url.indexOf("?"));
var param1 = Url+"?ordername="+ordername;
IFrame.setSrc(param1);
}
Try to use following code:
function forwardValues(){
var ordername = Xrm.Page.getAttribute("name").getValue();
var IFrame = Xrm.Page.ui.controls.get("IFRAME_sendvalue");
var Url = IFrame.getSrc();
if (Url.indexOf("?") != -1)
Url = Url.substr(0, Url.indexOf("?"));
var param1 = Url+"?ordername="+ordername;
IFrame.setSrc(param1);
}

How do I trigger events using Meteor server side events

I am using Meteor, which uses Mongodb as its database. I have code that inserts several documents into a collection when users fill out a form. When these documents are inserted, I would like to fire some JavaScript code within the server side directories that sorts through the collection in question for documents with matching fields as the documents just inserted.
My problem is that I do not know how to fire code on the server when the new documents arrive. Would it make sense to Meteor.call a Meteor.method at the end of the code involved with inserting, with the Meteor.method called preforming the sorting code I need?
Edit:
As you can see, in the below code I'm not calling any Meteor methods as none exist yet. The vast majority of this code is simply lead up for the insert({}) at the end of the page, so I think it can be safely ignored. The only server side code I have is to declare the possibleGames mongo collection.
I am not sure what you mean by call a plain JavaScript function, my problem is getting any code firing at all.
possibleGames = new Mongo.Collection("possibleGames");
Template.meet_form.events({
"submit .meet_form": function(event, template){
event.preventDefault();
var user = Meteor.userId();
var where = event.target.where.value;
var checkedGames = [];
function gameCheck (game) {
if (game.checked === true){
checkedGames.push(game.value);
};
};
var checkedDays = [];
function dayCheck (day) {
if (day.checked === true){
checkedDays.push(day.value);
};
};
console.log(event.target.where.value)
gameCheck(event.target.dnd);
gameCheck(event.target.savageWorlds);
gameCheck(event.target.shadowRun);
console.log(checkedGames);
dayCheck(event.target.monday);
dayCheck(event.target.tuesday);
dayCheck(event.target.wednesday);
dayCheck(event.target.thursday);
dayCheck(event.target.friday);
dayCheck(event.target.saturday);
dayCheck(event.target.sunday);
console.log(checkedDays);
var whereWhat = [];
for (i = 0; i < checkedGames.length; i++) {
var prepareWhereWhat = where.concat(checkedGames[i]);
whereWhat.push(prepareWhereWhat);
};
console.log(whereWhat);
var whereWhatWhen = [];
for (a = 0; a < whereWhat.length; a++) {
var prepareWWW1 = whereWhat[a];
for (b = 0; b < checkedDays.length; b++) {
var prepareWWW2 = prepareWWW1.concat(checkedDays[b]);
whereWhatWhen.push(prepareWWW2);
};
};
console.log(whereWhatWhen);
for (i = 0; i < whereWhatWhen.length; i++) {
possibleGames.insert({
game: whereWhatWhen[i],
user: user,
created_on: new Date().getTime()
})
}
}
});
You don't need to do a meteor.call on the server because you're already on the server.
Just call a plain javascript function.
If what you want to call from your first Meteor.method is already in another Meteor.method, then refactor that function to extract out the common bit.
Some code would also help if this is still confusing.

Posting data into JavaScript from an URL

I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();

Categories