Getting the content of specific element using YQL - javascript

I use the code below to load a page using YQL :
$(document).ready(function() {
var url = "http://www.google.com";
$.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) {
$('#container').html(data.results);
alert('Finish');
$('#container2').text($('#container #hplogo').attr('alt'));
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container" style="background-color:#eee;max-height:200px;overflow:scroll;background-color:#eee;">
All Page
</div>
<div id="container2">
Specific Content
</div>
You can see it loads Google website, but I don't know why it stops before executing Alert('Finish'); command. I want to extend my code to get the content of specific element inside the data.results after that.
Any help would be appreciated.

Related

My javascript is returning this error: $.ajax is not a function

Not sure what's wrong but I'm getting this error from my chrome console:
jquery-3.2.1.slim.min.js:1244 jQuery.Deferred exception: $.ajax is not a function TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (file:///C:/Users/Adam/Desktop/UseTime/js/example.js:3:7)
at j (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1193:55)
at k (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1199:45) undefined
r.Deferred.exceptionHook # jquery-3.2.1.slim.min.js:1244
jquery-3.2.1.slim.min.js:1247 Uncaught TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (example.js:3)
at j (jquery-3.2.1.slim.min.js:1193)
at k (jquery-3.2.1.slim.min.js:1199)
From this JavaScript:
$(function() { //when the DOM is ready
var times; //declare global variable
$.ajax({ //set up request
beforeSend: function (xhr) { //before requesting data
if (xhr.overrideMimeType) { //if supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
//funciton that collect data from the json file
function loadTimetable() { //decalre function
$.getJSON('data/example.json') //try to collect json data
.done(function (data) { //if succesful
times = data; //store in variable
}).fail(function () { //if a problem: show message
$('#event').html('Sorry! we couldnt load your time table at the moment');
});
}
loadTimetable(); //call the function
//CLICK ON TEH EVENT TO LOAD A TIME TABLE
$('#content').on('click', '#event a', function (e) { //user clicks on place
e.preventDefault(); //prevent loading page
var loc = this.id.toUpperCase(); //get value of id attr
var newContent = "";
for (var i = 0; i < times[loc].length; i++) { // loop through sessions
newContent += '<li><span class = "time">' + times[loc][i].time + '</span>';
newContent += '<a href = "descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display Time
$('#event a.current').removeClass('current'); // update selected link
$(this).addClass('current');
$('#details').text('');
});
//CLICK ON A SESSION TO LEAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function (e) { //click on session
e.preventDefault(); // prevent loading
var fragment = this.href; //title is in href
fragment = fragment.replace('#', ' #'); //Add Space before #
$('#details').load(fragment); //to load info
$('#sessions a.current').removeClass('current'); //update selected
});
//CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function (e) { //click on nav
e.preventDefault(); //prevent loading
var url = this.href; //get UR: to load
$('nav a.current').removeClass('current');
$(this).addClass('current');
$('#container').remove(); //remove old
$('#content').load(url + ' #container').hide().fadeIn('slow'); // add new
});
});
I'm not sure if it's an issue with the way I'm initiating .ajax or if my jquery isn't correctly implemented. I think it is. Any Thoughts?
edit: here's the html that goes with the script above
<!DOCTYPE html>
<body>
<header>
<h1>UseTime</h1>
<nav>
HOME
PROFILE
MANAGE TASKS
TIME TABLE
</nav>
</header>
<section id="content">
<div id="container">
<div class="third">
<div id="event">
<a id="class1" href="class1.html"><img src="" alt="class1" /> Class 1 </a>
<a id="class2" href="class2.html"><img src="" alt="class2" /> Class 2 </a>
<a id="class3" href="class3.html"><img src="" alt="class3" /> Class 3 </a>
</div>
</div>
<div class="third">
<div id="sessions"> Select a Class from the left </div>
</div>
<div class="third">
<div id="details"> Details </div>
</div>
</div>
<!-- container -->
</section>
<!-- content -->
<script src="js/jquery-3.2.1.slim.min.js"></script>
<script src="js/example.js"></script>
</body>
You are using slim version of jQuery. It Doesn't support ajax Calling.
Use
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
instead of it.
Slim build
Sometimes you don’t need ajax, or you prefer to use one of the many
standalone libraries that focus on ajax requests. And often it is
simpler to use a combination of CSS and class manipulation for all
your web animations. Along with the regular version of jQuery that
includes the ajax and effects modules, we’ve released a “slim” version
that excludes these modules. All in all, it excludes ajax, effects,
and currently deprecated code. The size of jQuery is very rarely a
load performance concern these days, but the slim build is about 6k
gzipped bytes smaller than the regular version – 23.6k vs 30k. These
files are also available in the npm package and on the CDN:
https://code.jquery.com/jquery-3.1.1.slim.js
https://code.jquery.com/jquery-3.1.1.slim.min.js
Referred from jQuery Blog
jQuery 3 slim version doesn't support ajax.
According to the release docs,
Along with the regular version of jQuery that includes the ajax and
effects modules, we’re releasing a “slim” version that excludes these
modules. All in all, it excludes ajax, effects, and currently
deprecated code.
To use .ajax method, simply use the full version one.
Try this one (jquery-3.2.1.min.js) instead of slim (jquery-3.2.1.slim.min.js)
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Jquery/Ajax - Get Picture and Youtube in HTML

So i'm back here again trying to figure out how to use HTML correct and can't get it to work correctly after been trying many hours with this.
Anyways, i'm trying to make so the picture and youtube trailer should be shown in the HTML and what I search for is something like this.
Right now im searching to make something like the picture but to get picture to be shown and a player with the trailer
so basically I want it to look similar like picture number one and I have come so far:
<!DOCTYPE html>
<html>
<head>
<title>Movies</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function callAjax(input)
{
var url = "http://localhost:1337/search/" + input;
$.ajax({
type:'GET',
url: url,
success: function(data)
{
console.log('SUCCESS');
$('#title').html("Title: " + data.title);
$('#release').html("Release: " + data.release);
$('#vote').html("Vote: " + data.vote);
$('#overview').html("Overview: " + data.overview);
$('#poster').html("Poster: " + data.poster);
},
error: function(request, status, err)
{
console.log('ERROR');
}
});
}
$(document).ready(function(){
$('#get-json').on('click', function(e){
e.preventDefault();
var input = $('#data').val().trim();
callAjax(input);
});
});
</script>
<body>
<center>
<div>
<input type="text" id="data" name="data" size="15" maxlength="120" />
<button type="submit" value="search" id="get-json">Search</button>
</div>
</center>
<section>
<div id="json-output"></div>
<div id="title"></div>
<div id="release"></div>
<div id="vote"></div>
<div id="overview"></div>
<div id="poster" img src="data.poster" style="width:104px;height:142px;"></div>
</section>
</body>
</html>
Also forgot to say that i'm very new at this, never done HTML really before and been trying to figure out this for a while without a result :(
You need to create placeholders for your JSON elements. At first write without that JSON a sample of HTML page that will look like you want. That page should have elements (for example div) for title, release and so on. Those elements should have its class or ids to be addressed (as it is already with <div id="json-output">)
You do not have to stringify your JSON. It is better to work JSON, since you can address its elements. For example, to set value into specific placeholder element you can use:
$('#title').html(data.title);
$('#relese').html(data.release);
$('#vote').html(data.vote);
JSON.stringify will return the contents of a JSON object as a string. It will not parse your JSON object and return HTML.
You can create a simple list like this:
function(data){
var $list = $('<ul>');
$list.append('<li>Title: ' + data.title + '</li>');
$list.append('<li>Release: ' + data.release + '</li>');
$list.append('<li>Vote: ' + data.vote + '</li>');
$list.append('<li>Overview: ' + data.overview + '</li>');
$('#json-output').html($list);
}

adding piece of HTML code using JS based on URL accessed

What I am trying to achieve is if a particular page is loaded in the browser for e.g www.domain.com/page then the following piece of code should be added in the page dynamically using JS (similar to how we load the Google Analytics code)
<div id="something">
<img src="http://domain.com/images/someImage.jpg">
</div>
I am trying to figure the script which will load the above mentioned HTML code (anywhere of the page - www.domain.com/page)
Edit 1:
what I am trying to achieve is when the user goes to www.domain.com/page.html I am calling another page lets say page1.html which should contain the script which insert the HTML code I posted above. So I simply want to insert the function which should be enclosed in the tag inside page1.html. Unfortunately I can not edit www.domain.com/page.html
If you want to PLACE that code anywhere in your page using javascript, you first need to identify that PLACE in DOM Using an "id" attribute. Here's an example:
HTML:
<html>
<body>
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
JS:
var html = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
document.getElementById('target1').innerHTML = html;
document.getElementById('target2').innerHTML = html;
You can try something like this :
$(document).ready(function () {
var url = window.location.href;
$("#something").append("<img src='"+ url +"' />");
});
$(".documentholder").load("code.html");
If you a specific id of something
$(".documentholder").load("code.html #someid");
If you a specific tag and id of something
$(".documentholder").load("code.html #someid");
Here you are,
just change this part if (getFileName() == "js") with if (getFileName() == "page")
I added js because that is what is returning in the code snippet :)
function getFileName() {
var url = document.location.href;
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
url = url.substring(url.lastIndexOf("/") + 1, url.length);
return url;
}
var div = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
if (getFileName() == "js") {
$('body').append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
let's say you save this code in a html-file named something.html
$(".documentholder").load("something.html");
in this case the class "documentholder" is the container you put the code in

JSON - get facebook total count from url

This script takes the number of likes from a facebook fan page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/tenniswarehouse?callback=?";
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<ul><li>" + json.likes + "</li></ul>";
//A little animation once fetched
$('.facebookfeed').animate({opacity:0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity:1}, 500);
});
});
</script>
</head>
<body>
<div class="facebookfeed">
<h2>Loading...</h2>
</div>
</body>
</html>
Source
I tried to make him take the total number of likes,shares and comments from a url("total_count") , but it didn't work.
<script type="text/javascript">
$(function() {
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url= %27http://www.google.com%27?callback=?";
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<ul><li>" + json.total_count + "</li></ul>";
//A little animation once fetched
$('.facebookfeed').animate({opacity:0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity:1}, 500);
});
});
</script>
</head>
<body>
<div class="facebookfeed">
<h2>Loading...</h2>
</div>
</body>
</html>
Could you please help me make the script get the "total_count" from links?
I guess
var html = "<ul><li>" + json.data[0].total_count + "</li></ul>";
should do... Be sure to remove surplus spaces from the URL in the FQL as well.
Have a look at this Fiddle: http://jsfiddle.net/e24ey/1/

populating div from external file div with javascript and jquery

Very frustrated here. Can't get this to work and don't know why.
I am trying to populate my div with a div from another html file. Here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="text">
content goes here
</div>
<script type="text/javascript">
function whenButtonClicked() {
var book = document.getElementById("book").value; //this is working
var chapter = document.getElementById("chapter").value; //this is working
var filename = 'files/' + book + chapter + '.html'; //this is working
$('#text').load(filename #source); //this is NOT
}
</script>
Thanks for any help.
Adam
Edit: Here is a link to the actual file I am working on. There may be something wrong in it as well.
Use this code: $('#text').load(filename + " #source");.

Categories

Resources