How to fix JAVASCRIPT | Random URL - javascript

<script type="text/javascript">
var page = 'index.html';
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1)
result.push(e);
});
return result;
}
function getrandom(data) {
return data[Math.floor(Math.random() * data.length)];
}
function sharenow() {
shared = true;
wopen('http://www.facebook.com/sharer.php?u=http://newomgvideos.com/anne-curtis/' + page, 'sharer', 500, 500, 'no', 'no');
}
$(document).ready(function() {
$('.button').click(function() {
if (redirect == true) {
window.location.href = 'https://www.facebook.com/';
} else {
$('#locker').show();
$('#popup-share').show();
}
});
$.get('pages.txt', function(data) {
pages = unique(data.split('page = getrandom(pages);
})
});
</script>
I have this code above it will randomly choose a link in page.txt. But i badly want to know how to make it instead choosing random link in page.txt i will just manually input all other urls in the code something like insert all the other links inside the code.
$.get('pages.txt', function (data) {
insert first url here>
insert second url here>
insert third url here>
insert fourth url here>
insert fifth url here>
pages = unique(data.split(' '));
page = getrandom(pages);
})
Your help is muchly appreciated. Thank you so much. Plss HELP.

First, you should split the text correctly to get a list of urls. I assume you have one URL on each line. Then data.split('\n') helps us with the array. I think you are looking for a random element in this array. This link might be a help:
Get random item from JavaScript array
And,this would be the code:
jQuery:
$.get('pages.txt', function(data){
pages = data.split('\n');
page = getrandom(pages)
// or page = pages[Math.floor(Math.random()*pages.length)];
// ... rest of your code ...
});

Related

Collecting title from youtube using api give strange behavior in jekyll

I used following code to get youtube title in my jekyll blog.
<script type="text/javascript">
function getyoutubetitle(videoID) {
$.getJSON('https://www.googleapis.com/youtube/v3/videos?id='+videoID+'&key=AIzaSyDfqskjJZVzNMKVs1c7dXvlDC2rpjrB60&part=snippet&callback=?',function(data){
if (typeof(data.items[0]) != "undefined") {
document.write(data.items[0].snippet.title);
} else {
console.log('video not exists');
}
});
}
</script>
When using <script>getyoutubetitle("iClTTtecJhs");</script> I get page reloaded to give only the title of video and all other content of blog gone.
http://songs.justinechacko.in/malayalam/2018/02/01/file5.html
Your bug is that you're just writing to the page. You need to rewrite the specific HTML node of wherever you want to display the title.
For example, if you want to change the text of a header with the id videoTitle01, then you would do:
<script type="text/javascript">
function getyoutubetitle(nodeID, videoID) {
let node = '#' + nodeID;
let apiKey = 'AIzaSyDfqskjJZVzNMKVs1c7dXvlDC2rpjrB60';
let url = 'https://www.googleapis.com/youtube/v3/videos?id=' + videoID + '&part=snippet&key=' + apiKey;
$.getJSON(url, function(data){
if (data && data.items && data.items[0]) {
$(node).text(data.items[0].snippet.title);
} else {
console.log('video not exists');
}
});
}
</script>
...
<script>
getyoutubetitle('videoTitle01','iClTTtecJhs');
</script>
<h1 id="videoTitle01"><h1>

How get specific html from a jQuery object

I am fetching html from a website. I want to get specific html from that page not all how to get that? I have tried following;
before appending data to target below
container.html(data);
I want to do like data.find('.site-header').html(); and then do container.html(data);
How can I achieve that?
DEMO
HTML
<div id="target"></div>
Script
$(function () {
var container = $('#target');
var url = 'http://aamirshahzad.net';
$.getJSON("http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) +
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg).focus().effect('highlight', {
color: '#c00'
}, 1000);
}
});
});
function filterData(data) {
// filter all the nasties out
// no body tags
data = data.replace(/<?\/body[^>]*>/g, '');
// no linebreaks
data = data.replace(/[\r|\n]+/g, '');
// no comments
data = data.replace(/<--[\S\s]*?-->/g, '');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
// no script blocks
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
// no self closing scripts
data = data.replace(/<script.*\/>/, '');
// [... add as needed ...]
return data;
}
Quite simply;
container.html($(data).find('.site-header'));
Add this line after container.html(data);:
container.html(container.find(".site-header"));
Here is your updated JSFiddle

asynchronous HTTP (ajax) request works in script tag but not in js file

I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});

AJAX parse + Yahoo YQL returning no results?

I'm working on a script that gets all the <table> elements from an external website by going through Yahoo's YQL. This has worked fine recently, but it stopped working as of today. I'm not entirely sure why, all websites used to work with this code:
<script type="text/javascript">
$(document).ready(function () {
var container = $('#target');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"
+ "q=select%20*%20from%20html%20where%20url%3D%22"
+ encodeURIComponent(url)
+ "%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("body");
container.append(justTable);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#target').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('http://www.google.com');
});
</script>
I changed the url to google and changed it to find the <body> tag instead of <table> tags to better show its not working. I looked at the URL that it's requesting and it's not showing any content. Not sure what the problem is though.
Have you checked if the "external website" you have crawled has structural changes?
When it has worked before and now not anymore, then my tip is that the site structure has changed.
It looks like the problem was that YQL was down? I just tested it again and it worked out fine. I wish they would tell us in the future if an outage occurred.

Populating A Page with XML and Javascript/Jquery, checking if the url is the same as an xml tag

I need to create a javascript function that will write a page based on the url, so basically I am trying to create a javascript function that will check the url, and find the corresponding xml item from there.
The reason behind this is so that the html page can just be duplicated, renamed, and the xml updated, and the page will fill in everything else from the xml sheet.
please let me know whether this is the completely incorrect way to do it, of it there is a better way. thanks!!!
XML CODE::
<!--XML INFORMATION-->
<channel>
<design>
<motion><!--design content-->
<item><!--//////////POST//////////POST//////////POST//////////-->
<tag>/portfolio_dec.html</tag>
<!--RSS INFORMATION-->
<title>Decoze</title>
<link>http://payamrajabi.com/portfoliotest.html</link>
<description><img src="http://payamrajabi.com/thumbs/small_jump.png" title="JUMP!." /></description>
<!--PROJECT CONTENT-->
<project><!--project start-->
<titl>TITLE</titl><!--project title-->
<dsc>PROJECT DESCRIPTION</dsc><!--project description-->
</project><!--project end-->
</item><!--//////////END//////////END//////////END//////////-->
</motion>
</design>
</channel>
JAVASCRIPT:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "code/content9.xml",
dataType: "xml",
success: function(xml) {
var xpathname = window.location.pathname;
var xproject = $(xml).find('tag').text();
if (xpathname == xproject) {
$(xml).find('item').children('tag').text(xpathname).each(function(){
var ttl = $(this).find('titl').text();
$('<p>'+ttl+'</p>').appendTo('h1#ttl');
});
$(xml).find('item').children('tag').text(xpathname).each(function(){
var dsc = $(this).find('dsc').text();
$('<p>'+dsc+'</p>').appendTo('h1#ttl');
});
} else {
PUT ERROR MESSAGE HERE
}
}
});
});
and THE HTML:
<html>
<head>
<script type="text/javascript" src="code/jquery-1.3.1.js"></script>
<script type="text/javascript" src="code/project/project_design.js"></script>
</head>
<body>
<h1 id="ttl"></h1>
<p id="dsc"></p>
</body>
</html>
any help would really be appreciated, i am frairly new to javascript/jquery/xml, and am really having trouble with this. The primary thing I want to do is have an xml file that populates a site, with each item being the content for a new page, in this case of a portfolio item.
cheers!
willem
Hmm... I'm afraid you don't quite understand how jquery works.
Your code should look something like this:
var xpathname = window.location.pathname;
var xitem = $(xml).find('tag:contains(' + xpathname + ')').parent();
if (xproject.length != 0) {
$('#ttl').append('<p>' + xitem.find('titl').text() + '</p>');
$('#dsc').append('<p>' + xitem.find('dsc').text() + '</p>');
}
else {
$('#err').text('The page you requested does not exist');
}
Demo 1
Here's a quick demo. Take a look at the source to see the XML and the JavaScript.
http://jsbin.com/ujiho#itemOne
http://jsbin.com/ujiho#itemTwo
http://jsbin.com/ujiho#itemThree
Demo 2
I've created another demo that uses $.get to retrieve the XML from a separate URL.
http://jsbin.com/aqefo#nov
http://jsbin.com/aqefo#dec
The XML: http://jsbin.com/afiwa
Here's the JavaScript. Let me know if you need help understanding anything.
$(function(){
$.get(
'http://jsbin.com/afiwa',
function(xml){
var hash = window.location.hash.substring(1);
if ($.trim(hash) === '') {
showError();
return;
}
var xitem = $(xml).find('urlname:contains(' + hash + ')').parent();
if (xitem.length != 0) {
$('#ttl').append(xitem.find('titl').text());
$('#dsc').append( xitem.find('dsc').text());
}
else {
showError();
}
function showError() {
$('#err').text('The page you requested does not exist');
}
}
);
});

Categories