I have a webpage in which I want to display the articles headlines that I am fetching from NewYork Time API, I am using nodejs as well, but the problem is that my articles gets printed below the end of html, although it should be printed inside like the "SAMPLE TEXT" is getting printed, is there a way in which I can print it inside?
http://imgur.com/sNmbqeN
<div class="card">
<div class="header">
<h3 class="title"><center><b>Chronicle</b></center></h3>
</div>
<body>
<p id="headline">SAMPLE TEXT</p>
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.9/p5.js"></script>
<script>
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "removed",
'q': "Trump"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
var articles = result.response.docs;
for (var i=0; i<articles.length;i++)
{
document.createElement('div');
document.createElement("H1");
var h = document.createElement("H1");
var t = document.createTextNode(articles[i].headline.main);
h.appendChild(t);
document.body.appendChild(h);
}
}).fail(function(err) {
throw err;
});
</script>
</body>
Your articles are being inserted at the end of the page because that is what you are asking javascript to do in your "document.body.appendchild" line. If you want your retrieved articles to go in a specific div or p tag, do something like this:
<p id="articles">Articles listed below:</p>
<script>
var newArticle = document.createElement("div");
var h = document.createElement("H1");
h.appendChild(document.createTextNode("Header"));
newArticle.appendChild(h);
var t = document.createTextNode("New article text");
newArticle.appendChild(t);
document.getElementById("articles").appendChild(newArticle);
</script>
I can't test with your original code using the NYT api but you should be able to see how it's done at least with the code above.
Related
I have the following code below. I want to change the H2 message No results were found for this query: <em class="querytext">to something like "No results were found by hello world! without hard coding as I have no control of the piece of text in an HTML file, is their any way I can do this via an if condition CSS or JS to read the string then change the message on load of the page? something like if text == No results were found for this query: display "No results were found by hello world!.
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em></h2>
</div>
You could try DOM manipulation with JavaScript:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<script type="text/javascript">
function updateResultText(text) {
var resultTextEl = document.querySelector('.search-results > h2');
if(resultTextEl) {
resultTextEl.innerText = "No results were found by " + text;
}
}
</script>
<button onclick="updateResultText('hello world!')">Update Text</button>
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em>
</h2>
</div>
</body>
</html>
The JS you need is below:
function updateResultText(text) {
var resultTextEl = document.querySelector('.search-results > h2');
if(resultTextEl) {
resultTextEl.innerText = "No results were found by " + text;
}
}
You would then make the call to updateResultText with whatever you want the text following 'by ' to consist of.
Here's a solution that uses vanilla JS to change all h2 that are child of .search-results class:
for (let h2 of document.querySelectorAll('.search-results > h2')) {
if (h2.textContent.search('No results were found for this query') >= 0)
h2.textContent = 'No results were found by hello world!';
}
<div class="search-results">
<h2>No results were found for this query: <em class="querytext"></em>
</h2>
</div>
old JavaScript
var query = "" // Get the username from either the backend, URL, or any other way like simple login form to the local storage without backend
var newText = 'No results were found for this' + query ': <em class="querytext"></em></h2>'
var el = document.querySelector('.search-results h2').innerHTML = newText
ES5
const query = "" // Get the username from either the backend, URL, or any other way like simple login form to the local storage without backend
const newText = `No results were found for this ${query}: <em class="querytext"></em></h2>`
const el = document.querySelector('.search-results h2').innerHTML = newText
At end of your page put the following script tag :
<script type="text/javascript">
var elem= document.querySelector('.search-results > h2');
if(elem) {
if(elem.innerText.indexOf("No results were found for this query")>=0)
elem.innerHtml="anything You want !!";
}
}
</script>
then after that there should be </body></html> tags.
I made a small webpage that asks the user to enter the name of an actor and I was hoping to then display all of the movies the actor had appeared in. For my question, I've hard coded the api URL for the actor (Bradley Cooper).
How do I grab all of the movie titles, the release year, movie overview, and the movie poster value and display them all on the page? Right now, I'm only able to display one movie and for some strange reason, it's not the first movie mentioned in the json file.
I think I need to get the json data into an array but I'm not sure how to do that and I'm not sure how to then display more than one result on the page.
I appreciate any help and guidance you can provide.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="search_actor()">
<script>
function search_actor() {
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.cast).each(function(index, moviedata) {
// Movie Title
document.getElementById("movietitle").innerHTML = moviedata.title;
// Release Year
document.getElementById("releaseyear").innerHTML = moviedata.release_date.substr(0, 4);
// Movie Overview
document.getElementById("movieoverview").innerHTML = moviedata.overview;
// Movie Poster
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
document.getElementById("displaymovieposter").innerHTML = fullmovieposterpath;
});
}
});
}
</script>
<div id="movietitle"></div>
<div id="releaseyear"></div>
<div id="movieoverview"></div>
<div id="displaymovieposter"></div>
</body>
</html>
In your code you have single only one container to display the movie items.You need to loop over the response and dynamically create the movie cards.Also use css grid system to have more control over the movie card and their placement.
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
console.log(data)
let k = '';
data.cast.forEach(function (item) {
//Using template literal to create a movie card
k += `<div class='movie-card'>
<div>${item.original_title}</div>
<div><img src = 'https://image.tmdb.org/t/p/w500/${item.poster_path}'></div>
<div><span>${item.release_date}</span></div>
<div class='movie-desc'>${item.overview}</div>
</div>`
})
$('.movie-conatiner').append(k)
}
});
See complete working copy here at stackblitz
Currently, you are displaying data in single division, so data is getting overwritten.
Instead you need to dynamically build division in for each statement and then assign the entire data in home page.
Also create only single div in html part with id="main"
Below is the updated code with above change. Please give proper CSS to the divisions.
Code after getting json response
divcnt=1;
divdata="";
$(data.cast).each(function(index, moviedata) {
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
divdata += '<div id="test'+ divcnt +'"><div id="movietitle'+ divcnt +'">'+moviedata.title+'</div><div id="releaseyear'+ divcnt +'">'+moviedata.release_date.substr(0, 4)+'</div><div id="movieoverview'+ divcnt +'">'+moviedata.overview+'</div><div id="displaymovieposter'+ divcnt +'">'+fullmovieposterpath+'</div></div>';
});
document.getElementById("main").innerHTML = divdata;
OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>
A bookmarklet is a bookmark whose address is JavaScript code.
I would like to get the URL of the current page I am on and paste that into the text box of the Bing search page.
I can get the URL easily enough:
javascript:(function(){var%20url=window.location.href;alert(url);})();
But then how do I set the text box on the Bing page to my variable, url and then make it search?
This does not work:
javascript:(function(){var%20url=window.location.href;window.open%20("https://www.bing.com/search?q=&url");})();
Use the following bookmarklet code:
javascript:{window.location='http://bing.com/search?q='+encodeURIComponent(window.location.href)}
Of course you can do the way you have seen above. However, I have been in this situation where I wanted to control what to show from within my application.
Then I decided to connect my application from Bing API. The benefit is that it is free and you will not take user away from your website.
You will need to get the API Key from the Azure Market Place
Here is the code that you might want to give it a try , may be, in the future.
<html>
<head>
<title>BING API Integration</title>
<SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#searchButton').click(function(e){
$("#results").empty();
var query=$('#searchTerm').val();
if ( query) {
serviceOp = "Web";
search(query, serviceOp);
}
});
});
function search(query, serviceOp){
// your account key that youw ill get from https://datamarket.azure.com
var acctKey = '<Your Key>';
var rootUri = 'https://api.datamarket.azure.com/Bing/Search';
var requestUri = rootUri + "/" + serviceOp + "?$format=json&Query='" + query + "'";
$.ajax({
type: "GET",
url: requestUri,
headers: {
"Authorization": "Basic " + window.btoa(acctKey + ":" + acctKey)
},
}).done(function(o){
if ( o.d !== undefined){
var items = o.d.results;
for(var idx=0, len= items.length; idx < len; idx++ ){
var item = items[idx];
switch(item.__metadata.type){
case 'WebResult':
showWebResult(item);
}
}
}
});
}
// Shows one item of Web result.
function showWebResult(item) {
var p = document.createElement('p');
var a = document.createElement('a');
a.href = item.Url;
$(a).append(item.Title);
$(p).append(item.Description);
$('#results').append(a, p);
}
</script>
</head>
<body>
<label for="searchTerm">Search: </label>
<input id="searchTerm" type="text"/>
<button id="searchButton">Search</button>
<div id="results">
</div>
</body>
</html>
I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle