Javascript script for Chrome Console not working with https webpage - javascript

I am using a script to get specified contents of specific links on a webpage and it has worked fine before, but after the site changed to https, it has stopped working.
The script is as follows:
var URL = window.location.origin
var episodeLinks = $('table.listing a').map(function(i,el) { return $(el).attr('href'); });
$.ajaxSetup({async:false});
$.getScript("https://kissanime.com/Scripts/asp.js");
var login = "vergo777";
var api_key = "R_6a13f014b38f4f80a31cf7d80a7c18c7";
var long_url;
var startEpisode;
do {
startEpisode = prompt("Enter episode number you want to start from");
if(startEpisode <= 0 || startEpisode > episodeLinks.length) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var endEpisode;
do {
endEpisode = prompt("Enter episode number you want to end at");
if(endEpisode <= 0 || endEpisode > episodeLinks.length || endEpisode < startEpisode) {
alert("Episode number entered must be greater than 0 and lesser than total number of eps");
} else {
break;
}
} while(true);
var videoQuality = prompt("Enter video quality you want to download. Example - '960x720.mp4' (without the quotes)");
var i;
for (i = (episodeLinks.length - startEpisode); i >= (episodeLinks.length - endEpisode); i--) {
jQuery.ajax({
url: URL + episodeLinks[i],
success: function(result) {
var $result = eval($(result));
var stringStart = result.search("var wra");
var stringEnd = result.search("document.write");
var javascriptToExecute = result.substring(stringStart, stringEnd);
eval(javascriptToExecute);
$("body").append('<div id="episode' + i + '" style="display: none;"></div>')
$('#episode' + i).append(wra);
var downloadQualityOptions = $('#episode' + i + ' a').map(function(i,el) { return $(el); });
var j;
for(j = 0; j < downloadQualityOptions.length; j++) {
if(videoQuality === downloadQualityOptions[j].html()) {
long_url = downloadQualityOptions[j].attr('href');
console.log(i);
get_short_url(long_url, login, api_key);
}
}
},
async: false,
script: true
});
}
function get_short_url(long_url, login, api_key)
{
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url,
async: true
},
function(response)
{
console.log(response.data.url);
}
);
}
I am getting the error: Uncaught ReferenceError: asp is not defined(…)
Any help is very appreciated, thank you!

Related

document.getElementsByClassName(...)[0] not working

I'm making site in which I have to add some element but only when they contain class .addEvent but when I try document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")
It shows me this error in console (json[i].date is something like: 2019-11-06):
TypeError: document.getElementsByClassName(...).classList is undefined
And when I display date in console it shows as it should be.
Here is my whole javascript code, maybe it would help:
$(() => {
var event;
$.ajax({
type: "GET",
url: "getEvents.php",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(json) {
for (var i = 0; i < json.length; i++) {
console.log(document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"));
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")) {
document.getElementsByClassName(json[i].date)[0].innerHTML += " <br/><span class='event'>" + json[i].name + "<br/>" + json[i].place + "</span>";
document.getElementsByClassName(json[i].date)[0].style.backgroundColor = json[i].color;
document.getElementsByClassName(json[i].date)[0].style.color = "#ffffff";
document.getElementsByClassName(json[i].date)[0].style.fontWeight = "bold";
document.getElementsByClassName(json[i].date)[0].style.opacity = "0.6";
}
}
},
error: function(error) {
alert("error");
console.log(error);
}
});
var day;
var shown = false;
$("td.addEvent").click(function() {
if (shown == false) {
$(".addEventMenu").css("display", "block");
day = getDay($(this));
var clickedDay = document.getElementsByTagName("p");
clickedDay[1].innerHTML += day;
shown = true;
}
});
function getDay(input) {
return input.clone().children().remove().end().text();
}
$("button.addEventBtn").click(function(e) {
e.preventDefault();
var year;
var month = $(".month").val();
const regex = /[0-9]{4}/gm;
let m;
while ((m = regex.exec($(".date").text())) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
year = `${match}`;
});
}
var name = $(".eventName").val();
var description = $(".eventDescription").val();
var place = $(".eventPlace").val();
var startHour = $('.eventStartHour').val();
var endHour = $('.eventEndHour').val();
var color = $('.eventColor').val();
var userId = $('input.userId').val();
if (day < 10) {
day = "0" + day;
}
var date = year + "-" + month + "-" + day;
$.ajax({
url: 'addEvent.php',
data: {
'eventName': name,
'eventDescription': description,
'eventPlace': place,
'eventStartHour': startHour,
'eventEndHour': endHour,
'eventColor': color,
'eventDate': date,
'userId': userId
},
type: 'post',
success: function(data) {
},
error: function(request, status, error) {
alert(request, status);
}
});
});
$("p.closeEventMenu").click(function() {
$(".addEventMenu").css("display", "none");
var clickedDateDay = $("p.clickedDay").text();
clickedDateDay = clickedDateDay.replace(/\s+$/, '');
$("p.clickedDay").text(clickedDateDay.substring(0, clickedDateDay.length - 2));
shown = false;
});
});
You are not confirming that the element exists before trying to use it.
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"))
If no elements matching class json[i].date exist, this if will throw the exception.
You should confirm the selector is returning elements before trying to use any of them:
var elements = document.getElementsByClassName(json[i].date);
if(elements.length > 0 && elements[0].classList.contains("addEvent"))
This will confirm the element actually exists before attempting to gather any information (classList) from the element. Of course, whether or not the element exists depends on many other factors - but in this case it seems that there are not any elements matching the selector on the page.

How to add dynamically attribute value using Jquery?

I have logic where i am trying to add host url dynamically so it work in all env based on hosst, so below trying to find a file that is there in host but its never going into $.each statement , if call url directly http://18.35.168.87:6000/Sdk/wrapper-sdk/client/out.json it worked and rendered data, any idea what could have wrong in below code to achieve this task ?
main.js
function myFunction(val) {
var url = "../../wrapper-sdk/" + client + "/out.json";
if (window.location.hostname.indexOf("localhost") !== -1 ||
window.location.host.indexOf("localhost") !== -1) {
var scripts = document.getElementsByTagName('script');
var host = '';
$.each(scripts, function (idx, item) {
if (item.src.indexOf('Sdk/wrapper-sdk') !== -1 && (item.src.indexOf('out.json') !== -1)) {
host = item.src.split('?')[0];
host = host.replace('wrapper-sdk/' + client + '/out.json', '');
}
});
url = url.replace('../../', host);
}
$.ajax({
url: url + "?no_cache=" + new Date().getTime(),
dataType: "json",
"async": false,
success: function (data) {
console.log(data);
},
error: function () {
console.log('error while accessing api.json.')
}
});
}
I would suggest breaking up some of your checks into their own function. Makes it just a bit easier to follow the logic.
function validIp(str) {
var parts = str.split(".");
var result = true;
$.each(parts, function(i, p) {
if (parseInt(p) > 0 && parseInt(p) < 255) {
result = result && true;
}
});
return result;
}
function checkLocalUrl(str) {
var result = 0;
if (str.indexOf("localhost") >= 0) {
result = 1;
}
if (validIp(str)) {
result = -1;
}
/*
0 = Some Domain or Host Name, not LocalHost
1 = LocalHost
-1 = IP Address
*/
return result;
}
function changeSources(client) {
if (checkLocalUrl(window.location.hostname) || checkLocalUrl(window.location.host) {
var scripts = $("script");
var host = '';
scripts.each(function(i, el) {
var src = $(el).attr("src");
var nUrl = new URL(src);
var pro = nUrl.protocol;
var hn = nUrl.hostname;
if (nUrl.pathname.indexOf('/Sdk/wrapper-sdk') == 0 && nUrl.pathname.indexOf('out.json') > 0) {
host = pro + "://" + hn + "/wrapper-sdk/" + client + "/out.json";
}
$.ajax({
url: host
data: { no_cache: new Date().getTime() },
dataType: "json",
async: false,
success: function(data) {
console.log(data);
},
error: function() {
console.log('error while accessing api.json.')
}
});
});
}
}
}
See also: new URL()
You can send a string to checkLocalUrl() and it will return 1 or true if it's potentially a localhost URL. It will return 0 or false if it's any other domain pattern or -1 or false if it's an IP address.
In changeSources() we can use this to check for local urls and perform the AJAX you defined.

Creating an image file dynamically with Javascript

I'm trying to create an image file dynamically, based on the contents retrieved from S3 Bucket. Got CORS working fine, here's the code I've written:
/**
* #name fetchFile
* #desc Fetch the desired file, and add to our _filesPending array, and update dialog process
* #author cgervais
*/
var _filesPending = [];
var _fileMessageDialog = "Currently downloading {{numberOfFiles}} videos...";
var _filesDownloadedSoFar = 0;
var _filesDownloaded = [];
var downloading = false;
function OKDownload(response, fileName) {
var responsePerfect = {
link: function() {
var _tmpResponse = JSON.parse(response);
return _tmpResponse.location;
}
};
$.ajax({
type: "GET",
url: responsePerfect.link(),
data: {},
success: function(answer) {
var _tmpFileObject = {
fUrl: fileName,
fContent: btoa(unescape(encodeURIComponent(answer.trim())))
};
_filesDownloaded.push(_tmpFileObject);
_filesDownloadedSoFar = _filesDownloadedSoFar + 1;
console.log('Downloaded -- so far: ' + _filesDownloadedSoFar);
},
error: function(response, errorCode, errorMessage) {
console.log('[OKDownload] ' + response + ' - ' + errorCode + ' - ' + errorMessage + ' // ' + responsePerfect.link);
}
})
}
var _alreadyGeneratedRStrings = [];
function generateReasonableString(min, max, fnMax) {
var _genStringSeed = Date.now() + 10;
var _randomString = '';
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=min; i < max; i++ )
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
_randomString = btoa(text + '::' + _genStringSeed);
if(_randomString.indexOf('==') > -1) {
_randomString = _randomString.replace('==','');
}
if(_randomString.length > fnMax) {
_randomString = _randomString.substring(0, fnMax);
}
if(_alreadyGeneratedRStrings.indexOf(_randomString) > -1) { _randomString = generateReasonableString(min, max, fnMax); }
_alreadyGeneratedRStrings.push(_randomString);
return _randomString;
}
function httpRawFetch(link) {
var matched = generateReasonableString(8, 26, 8) + ".jpg";
$.ajax({
type: "GET",
url: link.href + "&rawlink=yes",
data: {},
success: function(answer) {
if(answer === "") { console.log('[httpRawFetch] Failed fetching ' + link); return; }
OKDownload(answer, matched);
},
error: function(response, errorCode, errorMessage) {
console.log('[httpRawFetch] Error fetching JSON data from backend server.');
console.log('[DEBUG] ' + response + ' - ' + errorCode + ' - ' + errorMessage);
console.log('[DEBUG] Link: ' + link);
}
})
}
function generateDownloadModal() {
var _tmpHTML;
// #TODO: generate side modal with jQuery
}
function downloadFinished() {
var zip = new JSZip();
var _runningCountOfFiles = 0;
var _runningAddFiles = true;
for(var i = 0; i < _filesDownloaded.length; i++) {
_runningAddFiles = true;
// zip create file ( fileName, fileContent )
zip.file(_filesDownloaded[i].fUrl, decodeURIComponent(escape(atob(_filesDownloaded[i].fContent))));
_runningCountOfFiles++;
}
var recInterval = setInterval(function() {
if(_runningAddFiles && _runningCountOfFiles == _filesDownloaded.length || _runningCountOfFiles > _filesDownloaded.length) {
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "recordings.zip");
_runningAddFiles = false;
clearInterval(recInterval);
});
}
}, 1000);
}
setInterval(function() {
if(downloading) {
if(_filesDownloadedSoFar === _filesDownloaded.length) {
downloadFinished();
downloading = false;
}
}
}, 60000);
function fetchFile(link) {
if(link === "") {
alert('Cannot download this file.');
return;
}
_filesPending.push(link);
httpRawFetch(link);
downloading = true;
}
The issue:
It creates the zip with files, then it downloads to my machine. I open the image file, I get an error (all of them): "We can't open this file"
What am I doing wrong? They're JPG images.

Count how many times i have the same word

My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);

post data using ajax and js

Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});

Categories

Resources