How to grab text from URL and place in JS array? - javascript

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.

Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

Related

Grease/tamper monkey script to look for specific HTML in page and alert

I would like a grease/tamper monkey script, that when I visit a page, it looks for the following HTML on the page, and if it is present alert.
<p>
<script
type='text/javascript'
src='https://site_im_visiting.com/?a(6 hex characters)=(numbers)'>
</script>
</p>
Additionally, I would like to look inside an array (of about 4k sites), to see if the site is in the array.
Figured it out on my own, but instead of looking for the HTML, looked for the URL of the src of the script block
var scripts = document.getElementsByTagName("script")
var expression = /.*\/\?a[a-f0-9]{6}\=\d+?/gi;
const domains =["something.com","google.com"]
for (var i = 0; i < scripts.length; ++i) {
var regex = new RegExp(expression)
var t = scripts[i].src
if (t.match(regex)) {
const url = new URL(t)
if(domains.includes(url.hostname)){
console.log(url.hostname)
}else{
alert(url.hostname)
}
}
}

Text to Html list

I want to make a html which will auto get the information for a *.txt file
something1
something2
something3
and output into this html file
<!DOCTYPE html>
<html>
<head>
<title>List</title>
</head>
<body>
<ul>
#here to output#
</ul>
</body>
</html>
I prefer to use JavaScript. Some help is appreciated.
You have to request the file using AJAX call. Then you need to iterate through each line of response and generate DOM element (li in this case) and input line inside of it. After that insert each li element into your ul list.
You can achieve it using jQuery as you are probably new to JavaScript it's probably the easiest way.
What you need to do is request the file first:
$.ajax('url/to/your/file', {
success: fileRetrieved
});
Now after the file is retrieved jQuery will call fileRetrieved method, so we have to create it:
function fileRetrieved(contents) {
var lines = contents.split('\n');
for(var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
Now for each line from the file function fileRetrieved will call createListElement function passing line of text to it. Now we just need to generate the list element and inject it into DOM.
function createListElement(text) {
var into = $('ul');
var el = $('<li></li>').html(text);
el.appendTo(into);
}
Of course you don't want to retrieve into element each time createListElement is called so just store it somewhere outside the function, it's your call, I'm just giving you the general idea.
Here is an example of the script (without AJAX call of course as we can't simulate it):
var into = $('#result');
function fileRetrieved(contents) {
var lines = contents.split('\n');
for (var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
function createListElement(text) {
var el = $('<li></li>').html(text);
el.appendTo(into);
}
var text = $('#text').html();
fileRetrieved(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This element simulates file contents-->
<pre id="text">
fdsafdsafdsa
fdsafd
safdsaf
dsafdsaf
dsafdsafds
afdsa
</pre>
<div id="result"></div>
Try this
<html>
<head>
<title>List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="renderTxt_list">
</ul>
<input type="button" id="lesen" value="Read Data" />
</body>
<script>
$(document).ready(function(){
$("#lesen").click(function() {
$.ajax({
url : "testTxt.txt",
dataType: "text",
success : function (data) {
$html = "";
var lines = data.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
$html += '<li>'+lines[i]+'</li>';
}
$("body ul").append($html);
}
});
});
});
</script>
</html>
You need to request the file first, and then append it to your chosen place in the document.
You can for example use jQuery's get (or any other function like the native fetch), and then inject it into the ul element:
$.get("*.txt").then(x => $("ul").html("<li>" + x.split('\n').join('</li><li>') + "</li>"))
Let's break this solution by steps:
First, we need to request the external file:
$.get("*.txt")
Read about jQuery's get here. Basicly it will request the file you asked for using network request, and return a promise.
In the Promise's then, we can do stuff with the request's result after it is resolved. In our case we want to first break it by lines:
x.split('\n')
split will return an array that will look like this: ["line 1, "line 2", "line 3"].
JS arrays have the join method, which concat them to string while putting the string you want between the items. So after we do this:
x.split('\n').join('</li><li>')
We only need to add the <li> element to the start and end of the string like this:
"<li>" + x.split('\n').join('</li><li>') + "</li>"
Finally we appent it to your chosen element using jQuery's html.

Dynamically change text based on URL input

I am using the following code to dynamically change the text on my clients website (www.mydomain.com.au):
<script type="text/javascript">// <![CDATA[
var url = window.location.toString();
var query_string = url.split("?");
if (query_string[1]) {
var params = query_string[1].split("&");
var param_item = params[0].split("=");
param_item[param_item[0]] = unescape(param_item[1]);
document.write(param_item["city"]);
} else {
document.write("24 Hour Glass Replacement");
}
// ]]></script>
It works perfectly fine on the index page. e.g. www.mydomain.com.au/?city=test
but when I am using the same code on other pages e.g. http://www.mydomain.com.au/Brisbane.html/?city=test I get a 404 error.
Appreciate any help
Remove the / before starting querystring. So,
try http://www.mydomain.com.au/Brisbane.html?city=test instead of http://www.mydomain.com.au/Brisbane.html/?city=test

HTML with XML using jQuery

i have xml file which contains lots of data. now i want to pick a price with some condition. i set a parameteres in javascript function but it is not giving desire result. i think it can be done through childnode but i didnot aware about that
XML file
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="PER" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="SYD" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
HTML page
<head>
<script type="text/javascript">
function myXml(origin, destination ) {
var x = xmlDoc.getElementsByTagName("flights");
for(i=0; i<x.length; i++) {
if (x[i].getAttribute('FrTLAs') == origin
&& x[i].getAttribute('destination') == destination) {
alert(x[i].getAttribute('price'))
}
}
}
</script>
</head>
<body>
click me
</body>
did u miss this??
xmlDoc=loadXMLDoc("flights.xml");
chk this page
http://www.w3schools.com/dom/prop_element_attributes.asp
the example2 is very clear how to use this
x=xmlDoc.getElementsByTagName("book")[0].attributes;
//here its would be getElementsByTagName("flights") in the loop
//then .attributes on it
// and then this
frtlas=x.getNamedItem("FrTLAs");
desti=x.getNamedItem("destination");
//and your code here
hope this helps

Little help with some (simple) Javascript code

I'm a newb when it comes to javascript. Perhaps somebody could help me with this. I assume it is not very complicated. This is what I would like:
<SCRIPT type=text/javascript>
var StandardURL = "http://site/Lists/test/AllItems.aspx";
</script>
<SCRIPT type=text/javascript>
var FilterURL = "http://site/Lists/test//AllItems.aspx?FilterField1=Judge&FilterValue1=";
</script>
var DynamicURL = FilterURL + DynamicUserInf (no space between it should be like one url link), dynamicuserinf contains different value depending on the user that is logged in no need to worry what is in it. It already contains a value befor this runs
var CurrentURL = current URL where this script is loading
<script language="JavaScript" type="text/javascript">
if (CurrentURL == StandardURL) { location.href= (DynamicURL);}
</script>
ElSE do nothing (i assume this is not neccarry with only one if statement)
Hopefully not much of a mess.
For getting current URL :
var CurrentURL = document.URL;
For joining/concatenating the variables (assuming that DynamicUserInf is a variable), you've already got it correct :)
var DynamicURL = FilterURL + DynamicUserInf;

Categories

Resources