I'm not sure how to get this to work so that it takes the variable from the getrandomvideos and uses it in the jquery statement. I want the user to press a button then have a name randomly chosen then submited to the jquery statement which would then format the JSON that is returned.
<!doctype html>
<html>
<head>
<title>Trove Basic Search</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<h2>Search Trove</h2>
<button type="submit" id="searchbtn">Search</button>
<hr />
<div id="output">
<h4>Search Results</h4>
</div>
<script type="text/javascript">
function getRandomVideo() {
var searches = [
'beethoven',
'mozart',
'beethoven',
'debussy',
]
var rand = Math.floor(Math.random()*videos.length);
var search = searches[rand];
return search
}
var apiKey = "jja10ssv4950uh65";
var searchTerm = getRandomVideo();
$(document).ready(function(){
// There is an issue with TROVE applications where the first search will result in nothing being returned
// To get around this, we perform a dummy submit. Not sure how to do this
$("#searchbtn").submit
$("#searchbtn").submit(function() {
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
console.log(url);
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.article, function(index, value) {
$("#output").append("<p>" + value.articleText +"</p>");
});
});
});
});
</script>
</body>
</html>
It could be better if you just put function inside ready function, and just use click function for your submit button like so :
$(document).ready(function(){
function getRandomVideo() {
var searches = [
'beethoven',
'mozart',
'beethoven',
'debussy',
];
// this should be searches.length
// var rand = Math.floor(Math.random()*videos.length);
var rand = Math.floor(Math.random() * searches.length);
var search = searches[rand];
return search
}
var apiKey = "jja10ssv4950uh65";
// just use click event
$("#searchbtn").click(function(e) {
// we disable default behavior of button
e,preventDefault();
// here we call the function every time submit button clicked
var searchTerm = getRandomVideo();
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
console.log(url);
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.article, function(index, value) {
$("#output").append("<p>" + value.articleText +"</p>");
});
});
});
});
In the current implementation, you are getting the name on page load, and that will be used every single time. To change it every time user clicks.
Replace the line with:
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
Get a new video every time this is called
var searchTerm = getRandomVideo();
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
Try this code:
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
Related
I am experimenting using in using $.ajax to use geolocation to input weather data into a page from Wunderground. I am able to successfully input weather data into my page when I manually enter my location into code using plain vanilla JS but want to take it a step further. I am running the following code and get an alert box asking for location but after clicking okay see no code updates to my HTML. When opening the console in dev tools I do not see any error messages.
var Geo={};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGeo,error);
}
else {
alert('Geolocation is not supported');
}
function error() {
alert("Cant find you");
}
function successGeo(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
function showPosition(position) {
var geoLat = position.coords.latitude;
var geoLong = position.coords.longitude;
var key = "8704dded63fc077d";
var ForecastURL = "http://api.wunderground.com/api/"; + key + "/forecast/q/" + geoLat + "," + geoLong + ".json";
var WeatherURL = "http://api.wunderground.com/api/"; + key + "/conditions/q/" + geoLat + "," + geoLong + ".json";
$.ajax({
url : WeatherURL,
dataType : "jsonp",
success : function(parsed_json) {
var temp_f = parsed_json['current_observation']['temp_f'];
document.getElementById("currentTemp").innerHTML = temp_f;
}
});
$.ajax({
url : ForecastURL,
dataType : "jsonp",
success : function(parsed_json) {
var fore_high = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit'];
var fore_low = parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit'];
document.getElementById("high1").innerHTML = fore_high;
document.getElementById("low1").innerHTML = fore_low;
}
});
} //ends showposition function
I have some div elements set up in the footer of index.html just so I can confirm the elements are being updated. I'll worry more about style and alignment later.
<footer> <!--//contains ajax weather data-->
<div id="high1"></div>
<div id="current_temp"></div>
<div id="low1"></div>
</footer>
I'm pretty stumped as to why I can't get a response, especially since I'm not picking up any errors in the console.
Hi I am working in grails ..
<g:link name="searchLink" controller="MRController"
action="ExcelExport">TEST GRAILS</g:link>
<script>
$(function() {
$('a[name="searchLink"]').bind('click', function() {
$(this).attr('href', $(this).attr('href') + '?startdate=' + start().StartDate +'&enddate=' + start().Enddate);
})
})
function start(){
var StartDate = $("#startDate").val();
var Enddate= $("#endDate").val();
return {StartDate:StartDate,Enddate:Enddate}
}
</script>
I have trying to get the following url
http://localhost:8077/Myproject/MRController/ExcelExport
?startdate=2017-05-21&enddate=2017-05-23
But when i click the link again i get the following url instead i want the link with new startdate and enddate value
http://localhost:8077/Myproject/MRController/ExcelExport?
startdate=2017-05-21&enddate=2017-05-23?startdate=2017-05-21&enddate=2017-05-23
Edited
I have tried with the following script to clear the parameters in the first call but i don't know how to make the script run one after another means first the url call work then the parameters will clear through the function
<script>
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url.substring(url.lastIndexOf('/') + 1);
//get the part after before ?
value = value.split("?")[0];
return value;
}
</script>
Don't change the original href attribute in your JS-code:
$('a[name="searchLink"]').bind('click', function() {
document.location = $(this).attr('href') + '?startdate=' + start().StartDate +'&enddate=' + start().Enddate;
})
Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected
Hi I'm trying to fetch the contacts from the phonebook using contact.find but i can't get it to work...
The addressbook is displayed and the when I choose a contact i get the ID but I don't get the rest of the information from this user that im trieng to alert in the onContactFound() function... what can be wrong??
<script type="text/javascript" charset="utf-8">
function pickContact()
{
var options = {};
navigator.contacts.chooseContact(onContactSelected, options);
}
function onContactSelected(id)
{
alert("Contact ID = " + id);
//TODO: How to look up the contact object by ID???
var options = new ContactFindOptions();
options.filter = "" + id;
var fields = ["id","displayName","addresses"];
navigator.contacts.find(fields, onContactFound, onContactFailure, options);
}
function onContactFound(contacts) {
alert(contacts.length + " contact(s) found"); //ex. 1 contact(s) found
alert("ID = " + contacts[0].id + ", Name = " + contacts[0].Name);
}
</script>
Property is name (or displayName), not Name, I suspect. Change contacts[0].Name.
I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}