How to add dynamically attribute value using Jquery? - javascript

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.

Related

How to deal with asynchronous problems in javascript

I want to display data stored in ch ! But my problem is that ch is displayed before the data is stored !
I think this is an Asynchronous Problems! How can I solve this problem.
When I try to get length of ch, I get always 0. Even if I store data statically in ch, I get the length 0.
I think this is an Asynchronous Problems! How can I solve this problem.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
$.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml",
success: function(xml) {
var stock = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function()
{
dossier = $(this).attr('dossier');
stock.push(dossier);
});
});
var ch = [];
for (var i = 0; i < stock.length; i++) {
$.ajax({
url: "/mySecondWebServiceURL" + stock[i],
type: "GET",
dataType: "xml",
success: function(xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
ch.push({
"nom": nom,
"matcle": matcle,
"dossier": dossier
});
if ($('#population').val() != null && firstIter == false) {
}
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
The problem is that you are not waiting for the second service to respond.
It should be something like this:
const deferreds = stock.map((stockItem) => {
//... your logic with ch.push here
return $.ajax({
// your call to the second service
});
});
$.when(...deferreds).then(() => {
// your code
// for (var key in ch) {
});
The approach I'd rather take is to break the code down and use Promises. You really should take your time to learn Promises. It's a JavaScript standard and what jQuery uses under the hood.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
return $.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml"
});
}
function getStockArray(xml) {
var stocks = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function() {
{
dossier = $(this).attr('dossier');
stocks.push(dossier);
});
});
});
return stocks;
}
function getStocks(stocks) {
return Promise.all(stocks.map(fetchStock));
}
function fetchStock (stock) {
return $.ajax({
url: "/mySecondWebServiceURL" + stock,
type: "GET",
dataType: "xml"
})
.then(formatStockInfo)
}
function formatStockInfo (xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
if ($('#population').val() != null && firstIter == false) {
}
return {
"nom": nom,
"matcle": matcle,
"dossier": dossier
};
}
function updateSelectMenu (ch) {
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
}
RechercheFiltrée()
.then(getStockArray)
.then(getStocks)
.done(updateSelectMenu);

jQuery Promise each loop

I am creating a UserScript that will generate a list of URLs to a users photo gallery. A user gallery may have multiple pages, each page has multiple thumbnails that have a link to a page which contains the full-sized image url.
I am using jQuery to request the pages though I'm not getting the desired results when a user gallery only contains 1 page. I get some results when a user gallery contains multiple pages but I only get 1 page worth of results.
var userID = 0;
function getUserID() {
var query = window.location.search;
var regex = /UserID=(\d+)/;
var regexResult = query.match(regex);
if (regexResult !== null) {
return regexResult[0].replace('UserID=', '');
} else {
return 0;
}
}
function getGallery(userID) {
function getGalleryPage(userID, page, gallery) {
var data = {};
if(page > 0) {
data = { btnNext: ">", PageNo: page };
}
var url = 'http://www.domain.com/' + userID;
return $.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'html'
}).then(function(result){
$result = $(result);
$result.find('form[name="frmGallery"]').find('img').each(function() {
var url = ''
// Do stuff to get url
getGalleryImage(url).done(function(imageLink) {
gallery.push(imageLink);
});
});
$btnNext = $result.find('input[name="btnNext"]');
if($btnNext.length > 0) {
page += 1;
return getGalleryPage(userID, page, gallery);
} else {
return(gallery);
}
});
}
return getGalleryPage(userID, 0, []);
}
function getGalleryImage(url) {
return $.ajax({
method: 'GET',
url: url,
dataType: 'html'
}).then(function(result){
var imageUrl = '';
// Do stuff to get full sized image url
return imageUrl;
});
}
jQuery(document).ready(function($) {
userID = getUserID();
if(userID === 0)
return;
getGallery(userID).done(function(gallery) {
$.each(gallery, function(index, value) {
console.log(value);
});
});
});
I think this part of my script is not correct:
$result.find('form[name="frmGallery"]').find('img').each(function() {
var url = ''
// Do stuff to get url
getGalleryImage(url).done(function(imageLink) {
gallery.push(imageLink);
});
});
As written, there's no attempt to aggregate the inner promises returned by getGalleryImage().
You need to map the delivered img elements to an array of promises and aggregate them with jQuery.when().
I would write it something like this :
jQuery(function($) {
var userID;
function getUserID() {
var query = window.location.search;
var regex = /UserID=(\d+)/;
var regexResult = query.match(regex);
if (regexResult !== null) {
return regexResult[0].replace('UserID=', '');
} else {
return 0;
}
}
function getGallery(userID) {
var gallery = [];
var page = 0;
var url = 'http://www.domain.com/' + userID;
function getGalleryPage() {
var data = (page > 0) ? { btnNext: ">", PageNo: page } : {};
return $.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'html'
}).then(function(result) {
$result = $(result);
//map jQuery collection of img elements to Array of promises
var promises = $result.find('form[name="frmGallery"]').find('img').map(function(imgElement, i) {
var url = ''
// Do stuff to get url
return getGalleryImage(url);
}).get();// .get() is necessary to unwrap jQuery and return Array
//aggregate promises
return $.when.apply(null, promises).then(function() {
//accumulate results
gallery = gallery.concat(Array.prototype.slice.call(arguments));
// recurse/terminate
if($result.find('input[name="btnNext"]').length > 0) {
page += 1;
return getGalleryPage();
} else {
return gallery;
}
});
});
}
return getGalleryPage();
}
function getGalleryImage(url) {
return $.ajax({
method: 'GET',
url: url,
dataType: 'html'
}).then(function(result) {
var imageUrl = '';
// Do stuff to get full sized image url
return imageUrl;
});
}
userID = getUserID();
if(userID !== 0) {
getGallery(userID).then(function(gallery) {
$.each(gallery, function(index, value) {
console.log(value);
});
});
}
});
You should also impose a limit on the number of recursions, just in case one day some userID yields thousands of pages.

Javascript script for Chrome Console not working with https webpage

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!

If - else - Localstorage dont work / cordova

I want to check if its the first app start. I run my app via xcode on my iphone on usb. But everytime i close the app on iphone and start it again with clicking the icon on my phone - like a restart - it dont recognize that the app was startet before. What i am doing wrong?
$(document).ready( function() {
if (localStorage.getItem("applaunch")) {
window.localStorage.getItem("callstatus");
}else{
//Local storage is not set, hence first time launch. set the local storage item
window.localStorage.setItem('applaunch',1);
window.localStorage.setItem("vipstatus", "0");
window.localStorage.setItem("callstatus", "0");
}
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxxxxxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}
window.localStorage.setItem("username",generateUUID());
var username = window.localStorage.getItem("username");
var vipstatus = window.localStorage.getItem("vipstatus");
var callstatus = window.localStorage.getItem("callstatus");
$.ajax({
type: 'post',
url: 'http://www.bla.com/action.php',
data: {
data: {"username": username, "vipstatus" : vipstatus, "callstatus" : callstatus},
},
success: function(result) {
console.log(result);
}
});
});
Everytime i restart the app on the phone (NOT VIA XCODE BUILDING AGAIN) its making a new entry in my db - see ajax.
Set a variable that says whether it's the first time. Then only make the AJAX call when the variable is true.
$(document).ready( function() {
var first_time;
if (localStorage.getItem("applaunch")) {
first_time = false;
}else{
//Local storage is not set, hence first time launch. set the local storage item
window.localStorage.setItem('applaunch',1);
window.localStorage.setItem("vipstatus", "0");
window.localStorage.setItem("callstatus", "0");
first_time = true;
}
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxxxxxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}
if (first_time) {
window.localStorage.setItem("username",generateUUID());
}
var username = window.localStorage.getItem("username");
var vipstatus = window.localStorage.getItem("vipstatus");
var callstatus = window.localStorage.getItem("callstatus");
if (first_time) {
$.ajax({
type: 'post',
url: 'http://www.bla.com/action.php',
data: {
data: {"username": username, "vipstatus" : vipstatus, "callstatus" : callstatus},
},
success: function(result) {
console.log(result);
}
});
}
});

How to create a JSON feed

I have a file called parsing.html that parses through a xml feed and converts the metadata into JSON Object called "data". I'm trying to output this JSON "data" as a JSON feed such as http://www.videws.com/gtv/videosources.php. Is doing
document.write(JSON.stringify(data)) the equivalent of creating a JSON feed in this case?
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
//document.write(categories);
category.videos.push(video);
}
data.categories.push(category);
}
});
document.write(JSON.stringify(data));
}
})
im not sure you fully understand what http://www.videws.com/gtv/videosources.php is doing.
if you look at the source code it appears not to have any javascript at all so its not doing a document.write, it is more likely doing all of the conversion to JSON within PHP server side then streaming out.
a good help site for using PHP with JSON is available here: http://www.tutorialspoint.com/json/json_php_example.htm
i would say that if your more of a JS/HTML guru you may get more out of NODEJS than PHP but that's entirely up to you.

Categories

Resources