sending data from a search bar to a url - javascript

I am having trouble. So I need to get data from an api. I have a search bar and the user needs to input the search bar to look up a super hero api.
How would I get data from a search bar and put in my url all in a .click function.
var userInput;
var url;
var test;
//https://superheroapi.com/api/10215865526738981
$(document).ready(function () {
// when the user types in the data and clicks the button
$(btn1).click(function () {
// this is where the search bar is
userInput = document.getElementById('mySearch').innerHTML;
});
url = 'https://www.superheroapi.com/api.php/10215865526738981/search/batman' + userInput;
// here is where the api link in say type in batman
// and is should pop up with info about batman and
$.getJSON(url, function (data) {
var html = '';
$.each(data.results, function (i, demo) {
html += '<h2>' + demo.name + '</h2>';
//html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2> Power Stats ' + demo.powerstats.combat + '</h2>';
html += '<p> Connections ' + demo.connections.relatives + '</p>';
html += '<p> appearance ' + demo.appearance.gender + '</p>';
html += '<h2> Work ' + demo.work.base + '</h2>';
html += ' Profile <img src ' + demo.image.url + '>';
});
$('#demo').html(html);
});
}
<p>
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<p id="demo"></p>
</p>

Here is something that works that you can use to compare with your code and make something out of it. I've used plain javascript and left comments what is going on so that you can learn from it.
There were few wrong assumptions in original question.
code was executing on page load and didn't wait for user input
url was hardcoded to start with batman + what ever user wrote
Code below is not perfect, but it is close enough to original code and it should be easy to understand. I also opted not to use jQuery, but you should be able to use it if wanted. Just replace getElementById with jQuery selectors and replace XMLHttpRequest with getJson.
I hope this helps you move ahead with your problem and that you will be able to learn something new which could help you better understand javascript. Happy coding!
var button = document.getElementById('btn1');
// when user clicks on button, we want to call function start search
button.addEventListener('click', startSearch);
function startSearch(event) {
// when we are starting the search, we want to pick up the value
// input field from user
var userInputValue = document.getElementById('mySearch').value;
// this is base API url on which we can add what user wanted
var urlBase = 'https://www.superheroapi.com/api.php/10215865526738981/search/'
// if user did not provide name in input, we want to stop executing
if (userInputValue === null || userInputValue === '') return;
// if we are still in this function, append what user typed onto urlBase
var searchUrl = urlBase + userInputValue;
// call function which actually executes the remote call
performSearch(searchUrl);
}
function performSearch(searchUrl) {
// this could be jQuery getJSON if you so prefer
// here it is vanila JS solution of how to get data via AJAX call
var requestData = new XMLHttpRequest();
// because AJAX is always async, we need to wait until file is loaded
// once it is loaded we want to call function handleResults
requestData.addEventListener('load', handleResults);
requestData.open('GET', searchUrl);
requestData.send();
}
function handleResults() {
// once we get response, because we used vanilla JS, we got response
// available in this context as "this.response", however it is type string
// we need to take that string and parse it into JSON
var responseJSON = JSON.parse(this.response);
// if there is error, we didn't find any character
if (responseJSON.error) console.log('Character not found');
else {
var html = '';
responseJSON.results.forEach(function (result) {
html += '<h2>' + result.name + '</h2>';
// html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2>Power Stats ' + result.powerstats.combat + '</h2>';
html += '<p>Connections ' + result.connections.relatives + '</p>';
html += '<p>Appearance ' + result.appearance.gender + '</p>';
html += '<p>Work ' + result.work.base + '</p>';
// html += ' Profile <img src ' + result.image.url + '>';
})
// this is bad thing to do, injecting html like that into DOM
// but let's leave this lesson for later stage
// so, let's take this html and drop it onto the page
document.getElementById('demo').innerHTML = html;
}
}
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<div id="demo"></div>

const value = document.getElementById('mySearch').value;
And then use this value in your api url.

Related

Passing argument to on click event of dynamically generated element

I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.

Find all Divs after being created with JQuery on click event

I'm trying to find all divs that have been created from my click event and split them into another div (.wrapAll) on a count of 3. I can't seem to get anything back when i console.log the vars length. I know this works when I do that same process on the html thats been statically typed. Below is my code and thank you fo the thoughts!
jQuery(document).ready(function($) {
// load default twitch channels
$.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(data) {
//console.log(data);
});
// Bind 'Enter' to click event
$(document).bind('keypress', function(e) {
if (e.keyCode == 13) {
$('#search').trigger('click');
}
});
// manually search for games
$('#search').on("click", function() {
// clear previous results and get search term
$('#results').html('');
search = $('#searchTerm').val();
// begin API call
$.getJSON( "https://api.twitch.tv/kraken/search/streams?q=" + search + "", function(data2) {
// console.log(data2.streams.length);
data2.streams.forEach(function(entry) {
//console.log(entry._links);
var streamURL = entry.channel.url;
url = entry.preview.medium;
$('#results').append('<div class="searchResults"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game + '<br> Viewers: ' + entry.viewers +'<br> Is Mature: ' + entry.channel.mature + '<br> Status: ' + entry.channel.status + ' </p></div><hr>');
});
});
// Get 3 divs and slice into one div to style ** problem child **
var a = $('div[id^=searchResu]').find('div');
console.log(a.length);
for( var i = 0; i < a.length; i+=3 ) {
a.slice(i, i+3).wrapAll('<div class="slide"></div>');
}
});
});
Check out this plunker here. I believe this does what your looking for.
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
<script>
jQuery(document).ready(function($) {
function appendHtmlContent(resultHtmlContent) {
resultHtmlContent = '<div class="slide">' + resultHtmlContent + '</div>';
$('#results').append(resultHtmlContent);
}
function processSvcResponse(data2) {
var count = 0,
searchResultContents = '',
$div = $("<div>", { class: "searchResults"});
data2.streams.forEach(function(entry) {
var streamURL = entry.channel.url;
url = entry.preview.medium;
searchResultContents += '<div class="searchResults"><a href="' + streamURL
+ '" target="_blank"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game
+ '<br> Viewers: ' + entry.viewers + '<br> Is Mature: ' + entry.channel.mature
+ '<br> Status: ' + entry.channel.status + ' </p></a></div><hr>';
count++;
if(count === 3) {
appendHtmlContent(searchResultContents);
searchResultContents = '';
count = 0;
}
});
// more results that have not been appended?
if(searchResultContents) {
appendHtmlContent(searchResultContents);
}
}
// load default twitch channels
$.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(data) {});
// Bind 'Enter' to click event
$(document).bind('keypress', function(e) {
if (e.keyCode == 13) {
$('#search').trigger('click');
}
});
// manually search for games
$('#search').on("click", function() {
// clear previous results and get search term
$('#results').html('');
search = $('#searchTerm').val();
// begin API call
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=" + search, processSvcResponse);
});
});
</script>
</head>
<body>
<input id="searchTerm" type="text" />
<button id="search" type="button">Search</button>
<div id="results"></div>
</body>
</html>
If I understand correctly you are wanting to iterate over the results and for every third one wrap it inside a div with class "slider". As mentioned in the comments by #charlietfl in order to query newly created DOM elements using jQuery you have to query them after they are created. In the call to jQuery.getJSON the second argument accepts a callback function. The signature is jQuery.getJSON(url, someCallbackFunction). In order to make your code a bit more readable I moved "function(data2)" up and named it processSvcResponse. Inside processSvcResponse I build up an HTML string from the results and track how many results are processed by using a counter variable. Once the counter reaches 3 I append the contents to the results div and reset the counter. This solution does not "find" the divs and slice/wrapAll as you were intending to do originally, however, I believe this still accomplishes your goal.
As #charlietfl said, you'll need to place the code that wraps your divs in the callback for getJSON. Your click event listener would look something like this then:
$('#search').on("click", function() {
// clear previous results and get search term
$('#results').html('');
search = $('#searchTerm').val();
// begin API call
$.getJSON( "https://api.twitch.tv/kraken/search/streams?q=" + search + "", function(data2) {
// console.log(data2.streams.length);
data2.streams.forEach(function(entry) {
//console.log(entry._links);
var streamURL = entry.channel.url;
url = entry.preview.medium;
$('#results').append('<div class="searchResults"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game + '<br> Viewers: ' + entry.viewers +'<br> Is Mature: ' + entry.channel.mature + '<br> Status: ' + entry.channel.status + ' </p></div><hr>');
});
// Get 3 divs and slice into one div to style ** problem child **
var a = $('div[id^=searchResu]').find('div');
console.log(a.length);
for( var i = 0; i < a.length; i+=3 ) {
a.slice(i, i+3).wrapAll('<div class="slide"></div>');
}
});
});

How to add last.fm now playing into my site using Api

Hi guys i been trying to figure out for a long time but i suck at this, i found this code on google and i added it adn changed what i need but still doesnt work i really need this for my site: http://www.balkan-party.cf/
I found code here: http://www.samkitson.co.uk/using-json-to-access-last-fm-recently-played-tracks/
My last.fm username i need in js: alicajdin AND
Api key: 24f6b03517ad9984de417be5d10e150b
This is what i did:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=alicajdin&api_key=24f6b03517ad9984de417be5d10e150b&limit=2&format=json&callback=?", function(data) {
var html = ''; // we declare the variable that we'll be using to store our information
var counter = 1; // we declare a counter variable to use with the if statement in order to limit the result to 1
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
} // close the if statement
counter++ // add 1 to the counter variable each time the each loop runs
}); // close each loop
$('.listening-to h5').append(html); // print the information to the document - here I look for the h5 tag inside the div with a class of 'listening-to' and use the jQuery append method to insert the information we've stored in the html variable inside the h5 tag.
}); // close JSON call
});
I created that file and i tried to add on head section, footer section but it wont show recent tracks.
And yea i have scroblr installed on google crome
below </script> add the following code:
<div class="listening-to"></div>
then remove "h5" on
"$('.listening-to h5').append(html);"
so your code like this:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOUR_USERNAME&api_key=YOUR_API_KEY&limit=2&format=json&callback=?", function(data) {
var html = '';
var counter = 1;
$.each(data.recenttracks.track, function(i, item) {
if(counter == 1) {
html += 'Currently listening to: <span>' + item.name + ' - ' + item.artist['#text'] + '</span>';
}
counter++
});
$('.listening-to').append(html);
});
});
</script>
<div class="listening-to"></div>
Hope you can help. Sorry, my English is very Bad (Google Translate)

Pass string from one function to the next javascript

I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;

How can I display multiple (but seperate) JSON requests on the same page

I have a web page where I want to display hotel reviews from the yelp.com API for a number of hotels.
I have managed to do this for one hotel, and it works perfectly displaying the data under that specific hotel's details on the page. However, how can I now multiply this process so that I have separate reviews for each hotel?
My web page can be seen at http://dev.bhx-birmingham-airport.co.uk/pages/hotels.php to get an idea of what I'm trying to do.
The source code I am using so far looks like:
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>Review - ' + review.text_excerpt + ' Read more...</p>';
content += 'Rating - <img src="' + business.rating_img_url + '" />';
content += '<p>Date Added - ' + review.date + '</p>';
$(content).appendTo('#hilton');
});
});
}
$(document).ready(function(){
// note the use of the "callback" parameter
writeScriptTag( "http://api.yelp.com/business_review_search?"+
"term=hilton%20metropole"+
"&location=B26%203QJ"+
"&ywsid=[...]"+
"&callback=showData"); // <- callback
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
Your question is somewhat unclear.
I assume that you want to send multiple requests to Yelp and have them processed by different callback functions.
You can do that by making a buildCallback method that takes information about the request to generate a callback for and returns a function.
You can then use an invocation of that function as the callback parameter, like this: callback=buildCallback('something') It will return a script that looks like this:
buildCallback('something')({"message: ... })
This code calls the buildCallback method, then calls the function that the buildCallback method returns.
For example:
(Assuming that each hotel has a <div class="HotelReviews" id="giveThisToYelp">)
function buildCallback(hotelName) {
return function(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>Review - ' + review.text_excerpt + ' Read more...</p>';
content += 'Rating - <img src="' + business.rating_img_url + '" />';
content += '<p>Date Added - ' + review.date + '</p>';
$(content).appendTo('#' + hotelName);
});
});
};
}
$(function() {
$('.HotelReviews').each(function() {
$.getScript("http://api.yelp.com/business_review_search?"+
"term=" + this.id +
"&location=B26%203QJ"+
"&ywsid=[...]"+
"&callback=buildCallback(" + this.id + ")"
);
});
});
Instead of inserting a script tag on the page with the request url and a callback function name, You should make multiple requests to Yelp services manually.
A simple example in JQuery:
function LoadReviews() {
for (var i = 0; i < myhotels.length; i++) {
$.getJSON("http://api.yelp.com/business_review_search?" + myhotels[i], null, showData);
}
}
Where the myhotels array contains the search parameters for each of your hotels.

Categories