Cant display JSON data in html page - javascript

I'm working on an API App utilizing the Foursquare API. Using my getRequest,
Im getting my results in JSON, which Im displaying in my console.log.
The thing is, I don't know how to parse the JSON data and display what I want on my HTML page.
I'm trying to have the 'name' of the venues displayed, but I don't know how to do it.
P.S: I have a Math.random function on the incoming data from Foursquare, so whatever random venue name that is displayed in my console.log is what I want displayed in my HTML page.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search</title>
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js" type="text/javascript" id="jquery"></script>
<script type="text/javascript" src="apps/app.js"></script>
</head>
<body>
<H1>Hunger Pains</H1>
<p>Search for food cause you cant take it anymore</p>
<!--This is the area your location gets spit out on the html page-->
<p id="demo"></p>
<form id ="search-term">
<!--text entry field-
<input type="text" id="query">-->
<!--Submit button-->
<input id="submit" type="submit" value="submit">
<!--Search results div-->
<div id="search-results"></div>
</form>
</body>
</html>
Jquery:
$(document).ready(function(){
//document.getElementById("submit").disabled = false;
//When you click the submit button it fires off the getRequest.
$(function(){
$('#search-term').submit(function(event){
event.preventDefault();
//getRequest();
myFunction();
});
});
// This is the get request. It has a random function that randomizes the callback data. Once you get the randomizes data, it shows in the console window.
//This function displays three random results based on the myFunction below
function getRequest(){
$.getJSON('https://api.foursquare.com/v2/venues/search?v=20131016&ll=40.7%2C-74&intent=browse&radius=800&categoryId=4d4b7105d754a06374d81259&client_id=C2IEUINHBL2HEVOHIWNO0GGN5EUHK3PGYH03HCZRP2ETA4CF&client_secret=DOLF3UBQZOY5GX2DP3EXBQ5CW4AHEWMNDGRMH0IHJWZBDSIO', function(data){
var random = data.response.venues[Math.floor(Math.random() * data.response.venues.length)];
//showResults();
console.log(random);
});
}
//This is the function that calls getRequest function three times then stops.
function myFunction(){
var myVar = setInterval(function(){getRequest();}, 500);
//clearTimeout(myVar);
setTimeout(function( ) { clearInterval( myVar); }, 1600);
}
});

To get the name from the object you are getting from Foursquare use:
console.log(random.name);
And if you need the url for example use:
console.log(random.url);

Something like this should do it:
$("#search-results").append('<br>' + random.name);

Related

Get Element Breaking Code

I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?

Handlebarsjs : H1 tag won't display when submit button is clicked

I'm messing around with Handlebars.js and I'm doing a very simple example consisting of a tutorial from a website(the shoes section) and my own simple little template(the heading, where the problem is)
handlebardemo.html
<head>
<meta charset="ISO-8859-1" name="viewport" content="width=device-width, initial-scale=1">
<title>Handlebar demo</title>
<script src="lib/jquery-2.1.4.js" type="text/javascript"></script>
<script src="lib/jquery-ui.js" type="text/javascript"></script>
<script src="lib/handlebars-v4.0.4.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/w3.css">
<link rel="stylesheet" href="css/jquery-ui.css">
</head>
<body>
<div class="username-container">
<script id="heading-template" type="x-handlebars-template">
<h1 class="h1">Hello {{username}}</h1>
</script>
<input type="text" id="username">
<button type="submit" id="username-submit">Enter</button>
</div>
<h4 class="w3-row-padding">Shoe List:</h4>
<ul class="shoesNav w3-ul w3-text-indigo"></ul>
<script id="shoe-template" type="x-handlebars-template">
{{#each this}}
<li class="shoes">{{name}}--Price:{{price}} </li>
{{/each}}
</script>
</body>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
$(function (){
var shoesData=[{name:"Nike", price:199.00}, {name:"Loafers", price:59.00}, {name:"Wing Tip", price:259.00}];
//Get html from tempalte in script tag
var theTemplateScript = $("#shoe-template").html();
//Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
$(".shoesNav").append(theTemplate(shoesData));
//shoesData is passed to compiled handlebars function
//function inserts values from the objects in their respective places in the HTML
//and returned HTML: as a string. Then jQuery is used to append the resulting HTML string to the page
})
Im not sure if I'm using the handlbars syntax etc. correctly, but i based it mostly off of the second function in main.js, which came from a brief handlebars tutorial
When I click the Enter button, nothing happens. There are no console errors, it just does nothing. Am I going about this the wrong way, at least compared to the unordered list example?
EDIT: As per Elli Parks answer, I added an id to the submit button and changed the click handler assignment to the submit button rather than the textbox(a silly mistake on my part). The element still won't appear when the submit button is clicked
In main.js, you're attaching the click handler to #username, which is an input field. You need to give the Enter button an id (ex: #username-submit) and attach the click handler to the button.
So something like this:
handlebardemo.html
<button type="submit" value="Enter" id="username-submit" >Enter</button>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
You need to change two things:
fix the selector to target the button, like #ElliPark has already said
put the whole thing into the document-ready handler (ie, into the $(function () {...} ); construct. You are trying to attach the event listener before the DOM is ready.
See the demo on JSBin.

JavaScript assigned array values removed after invoking function

Using JavaScript to display a list of what was typed into the textarea element listed below. The values submitted are displayed for a split second, but are removed from the array right after the function is called. Would anyone care to explain why?
HTML
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<link rel='stylesheet' type='text/css' href='template.css'>
</head>
<body>
<header id='title'>
<h1></h1>
<h2></h2>
</header>
<div id='main_container'>
<div id='chat'>
<form id='messaging'>
<textarea id='current_msg'></textarea>
<input type='submit' value='send'>
</form>
<ul id='msg_list'>
</ul>
</div>
</div>
<script type='text/javascript' src='client.js'></script>
</body>
</html>
JavaScript
var msgList=[];
var form=document.getElementById('messaging');
var currentMsg=document.getElementById('current_msg');
var chat=document.getElementById('chat');
var ul=document.getElementById('msg_list');
function addText() {
if(currentMsg.value.length>0) {
if(msgList.length>=25) msgList.pop();
msgList.unshift(currentMsg.value);
currentMsg.value='';
console.log(msgList.length);
}
var concat='';
for(var index=0; index<msgList.length; index++) {
concat+='<li>'+msgList[index]+'</li>';
}
ul.innerHTML=concat;
}
if(document.addEventListener) {
form.addEventListener('submit', function() {
addText();
},
false);
}else {
form.attachEvent('onsubmit', function() {
addText();
},
false);
}
You need to understand the effects of having form:
1) User input some values
2) Once Submit the form get submitted , as you have not specified the action it will default to reload the current web page which means all inputs will be cleared
3) The html page get parsed from scratch , the JS code runs but it will only access the new values of inputs which are empty at this point
To make this work you need to remove the form tag

How to swap an H1 element from an H1 in another document using JQuery

Please bear with me because I'm student. My instructor had us watch 5 YouTube videos and now expects us to program using JQuery instead of standard JavaScript. All I want to do is swap an element with an element from another file.
Here's my HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Testing JQuery</title>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<h1 id="header">Testing JQuery</h1>
<p id ="dummy">Lorem Ipsum </p>
<script src="changes.js"></script>
<form name="input" action="changes.js">
<input type="button" value="Change the Header">
</form>
</body>
</html>
Here is my JavaScript/JQuery code:
$(document).ready(function() {
$('input').click(function() {
var url = $(this).attr('form');
$('#header').load( greeting.html + '#ajax h1');
return false;
});
});
The third file is called greeting.html and this is all it contains:
<h1 id="ajax">Hello from jQuery with AJAX</h1>
$('#header').load( 'greeting.html #ajax' );
That's all you need. Get rid of all the other stuff.
You dont need to declare url and you dont need to return false.
To replace the element, load() won't work as it loads the new H1 inside the old H1, it does not replace it, so you have to use $.get and do it yourself :
$(document).ready(function() {
$('input').on('click', function() {
$.get({
url : 'greeting.html'
}).done(function(data) {
var h1 = $('<div />').append(data).find('h1#ajax');
$('#header').replaceWith(h1);
});
return false;
});
});

Ajax in Tinybox 2

I have a Tinybox 2 popup opening when clicking 'register'. The user has then to choose if he/she wants to register as a user or a performer. I'd like to show a different registration page for each, but first asking it, so handling with ajax would be the best. It can be done, as shown here, in the 5th example. Here is my current code:
<!doctype html>
<html>
<head>
<title>Regisztrációs típus kiválasztása</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="../css/soon.css"/>
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
</head>
<body>
<div id="teljes">
<h1>Miként szeretnél regisztrálni?</h1>
<div id="felhasznalo">
Felhasználóként
</div>
<div id="eloado">
Előadóként
</div>
</div>
<script type="text/javascript">
$('#felireg').click(function() {
$.get("../php/register.php");
});
</script>
</body>
</html>
Thanks!
If i understand correctly, you want to make an ajax call to your registration file named "register.php" and show this in a Tinybox
$('#felireg').click(function() {
TINY.box.show({
url:'../php/register.php',width:300,height:150
})
});
This should work.
//EDIT :
Assuming your file returns only html:
$('#felireg').click(function() {
$.get("../php/register.php", function(data)
{
TINY.box.fill(data);
});
});
This should update the current Tinybox

Categories

Resources