Getting stock quote with JavaScript though yahoo's webservices - javascript

I need to create a simple web site that gets the stock value based on the ticket.
Input: CSCO Output: 23.49. I'm very new to both webservices and javascript. The current YQL statement I am using is: select * from yahoo.finance.quotes where symbol="CSCO" which does not work.
function getprice()
{
var symbol = $('#stockquote').val();
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22"+symbol+"%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json";
$.getJSON(url, function (json)
{
var lastquote = json.query.results.quote.LastTradePriceOnly;
$('#stock').text(lastquote);
});
}

Related

Auto-populate custom entity using javascript without knowing the guid value of the parent entity in Dynamics 365

I just started to use client side scripting, although it might me those another go to google search community question, but believe me I have scourged google and communities but to link my query into a single unit always fail, let me describe the problem statement to give you a better idea.
I have created two custom entity named cts_agent and cts_cases, now I need to auto populate all the fields of cts_cases which are read only property fields except one which is agent id (whole number) which is mapped to cts_agent entity form.
If it have been an entity reference field I could use the query expression to fetch the details from the agents_form and auto populate the details in my cts_form but I need to write a js query which could take the agent id and fetch me those details. After fetching the details will be presented in a json format from where I need to populate the details in my cts_cases form which is also another problem I am unable to address, the dynamic retrieval of guid value and auto-populating the cts_cases with json are my two blockage I am facing. I have written a code for static version though:
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/cts_agents(00000000-0000-0000-0000-000000000000)?$select=cts_addressline1,cts_addressline2,cts_addressline3,cts_city,cts_country,cts_email,cts_fax,cts_mobilenumber,cts_name,cts_phonenumber,cts_state,cts_zipcode", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response);
var cts_addressline1 = result["cts_addressline1"];
var cts_addressline2 = result["cts_addressline2"];
var cts_addressline3 = result["cts_addressline3"];
var cts_city = result["cts_city"];
var cts_country = result["cts_country"];
var cts_email = result["cts_email"];
var cts_fax = result["cts_fax"];
var cts_mobilenumber = result["cts_mobilenumber"];
var cts_name = result["cts_name"];
var cts_phonenumber = result["cts_phonenumber"];
var cts_state = result["cts_state"];
var cts_zipcode = result["cts_zipcode"];
var cts_zipcode_formatted = result["cts_zipcode#OData.Community.Display.V1.FormattedValue"];
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
you can configure a filter in the arguments.
you can also use the available Xrm.WebApi functions for simpler querying syntax
$filter=agentid eq 123
//where agentid is your integer identifier field
Example:
Xrm.WebApi.retrieveMultipleRecords("cts_agent","?$select=cts_addressline1,cts_addressline2,cts_addressline3,cts_city,cts_country,cts_email,cts_fax,cts_mobilenumber,cts_name,cts_phonenumber,cts_state,cts_zipcode&$filter=agentid eq 123")
.then(
result => {
//you read the results here - retrieve multiple returns an array of records.
if(result.entities.length > 0)
{
var cts_addressline1 = result.entities[0].cts_addressline1;
//etc...
}
},
err => {
console.error(err);
});
if you want the agent unique id (guid) you can just get it from result.entities[0].cts_agentid
the dynamic retrieval of guid value and auto-populating the cts_cases with json are my two blockage I am facing
You got assistance from another answer on the first part. Like explained, you will be able to query the entity record with any attribute value (unique) you know of.
For second part - once you get the guid, you will be able to pass that as a parameter to Xrm.Navigation.openForm which can be used to open cts_cases entity form, and on form load using this parameter - pull the details from agent record and assign the attribute values from json to the opened cts_cases form fields. Or you can pass the values (in case of minimal attributes) as parameters too while opening the form. Read more
var entityFormOptions = {};
entityFormOptions["entityName"] = "cts_cases";
// Set default values for the Contact form
var formParameters = {};
formParameters["cts_addressline1"] = result["cts_addressline1"]
//other attributes go here
// Open the form.
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});

Finding JSON key match with jQuery and PokéAPI

I'm trying to find and use an english translation of a language JSON endpoint using the PokéAPI in an app I am developing. I need to utilise translations when submitting a call to one of the urls shown below. Unfortunately, the english language key is not always in the same order in the array response so I need a way of finding and checking for it so that the correct english translation is shown on the front-end.
Im trying to retrieve:
flavor_text_entries[X].language.en key in each search and retrieve the flavor_text_entries[X].flavor_text to show the description on the front-end.
API URL 1:
https://pokeapi.co/api/v2/pokemon-species/3/
API URL 2:
https://pokeapi.co/api/v2/pokemon-species/10/
Code:
var pokeBio = $("[data-poke-bio]").html();
function submit(){
var pokeID = $("[data-poke-id]").val();
var pokeSpecURL = "https://pokeapi.co/api/v2/pokemon-species/" + pokeID;
$.ajax({
type: "GET",
url: pokeSpecURL,
success: function(dataSpec){
ajaxSpecSuccess(dataSpec);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
ajaxError();
}
});
}
function ajaxSpecSuccess(dataSpec){
var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;
var pokeBio = $("[data-poke-bio]").html(pokeMatchBio);
}
Snippet I need to manipulate:
var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;
Step 1, find the english entry
Step 2, display its flavor_text or a message if it wasn't found
let englishEntry = dataSpec.flavor_text_entries.find(entry => entry.language && entry.language.name && entry.language.name === 'en');
if (englishEntry) {
console.log(englishEntry.flavor_text);
} else {
console.log("English entry not found");
}

How to get temperature value on javascript (serverside)?

I was looking to use a weather API (like yahoo's) and make my javascript code able to return the temperature given a city.
My app runs on rivescript (built on javascript and node).
Researching I only found ways to do it locally on json, or by using html and css as well, but I just want a simple javascript code that returns a value with the temperature.
Thanks
You can try something like this, using openweathermap.org APIs:
function getWeather(city, callback) {
var url = 'http://api.openweathermap.org/data/2.5/weather';
$.ajax({
dataType: "jsonp",
url: url,
jsonCallback: 'jsonp',
data: { q: city },
cache: false,
success: function (data) {
callback(data.main.temp);
}
});
}
This example uses a name of a city as input, and returns temperature in K° degrees.
The data.main.temp value is returned, but you could return just data to have the whole weather object for that city.
Otherwise, if you want to use Yahoo Weather API (with your APPID):
function getWeather(position, callback) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// Yahoo's PlaceFinder API http://developer.yahoo.com/geo/placefinder/
// We are passing the R gflag for reverse geocoding (coordinates to place name)
var geoAPI = 'http://where.yahooapis.com/geocode?location='+lat+','+lon+'&flags=J&gflags=R&appid='+APPID;
// Forming the query for Yahoo's weather forecasting API with YQL
// http://developer.yahoo.com/weather/
var wsql = 'select * from weather.forecast where woeid=WID and u="'+DEG+'"',
weatherYQL = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&format=json&callback=?', code, city, results, woeid;
// Issue a cross-domain AJAX request (CORS) to the GEO service (not supported in Opera and IE)
$.getJSON(geoAPI, function(r) {
if (r.ResultSet.Found == 1) {
results = r.ResultSet.Results;
city = results[0].city;
code = results[0].statecode || results[0].countrycode;
woeid = results[0].woeid; // the the city identifier for the weather API
// Make a weather API request (it is JSONP, so CORS is not an issue):
$.getJSON(weatherYQL.replace('WID', woeid), function(r) {
if (r.query.count == 1) {
var item = r.query.results.channel.item.condition;
callback(item.temp
} else {
console.error("Error retrieving weather data!");
}
});
}
}).error(function(){
console.error("Sorry, your browser does not support CORS requests!");
});
}
This example uses a position as input (see navigator.geolocation), and returns temperature in C° degrees.
Note:
- both examples imply the use of jQuery.
- the second example implies having obtained a Yahoo APPID

Parse.com API not sharing URL link (other data comes fine)

I'm using Parse.com give people an ability to share a URL from the app, to an individual "object" in Parse.com.
The below code works fine- EXCEPT for some reason the "LINK" (URL) is not coming through. All the other data comes through.
Is there a trick with Parse and sharing URL's?
My HTML is fine, I"ve pasted my javascript below.
var url = document.URL;
var objectId = url.substr(url.lastIndexOf('/') + 1);
var name;
var designer;
var itemDescription;
var price;
var link;
var image;
Parse.initialize("xxx", "xxx");
var garmentsAPI = Parse.Object.extend("garmentsAPI");
var query = new Parse.Query(garmentsAPI);
query.get(objectId, {
success: function(garments) {
console.log("success");
name = garments.get("name");
designer = garments.get("designer");
itemDescription = garments.get("itemDescription");
price = garments.get("price");
link = garments.get("link");
image = garments.get("smallImage1");
$("#designer").html(designer);
$("#name").html(name);
$("#itemDescription").html(itemDescription);
$("#price").html(price);
$("#image").attr("src", image.url());
$("#buyButton").attr('href', link);
console.log(image.url());
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
console.log("fail");
}
});
if your column name of file is
smallImage1 then
you can get url of file is as follows:
smallImage1._url

How to use YQL to retrieve web results?

I am having difficulty setting up a simple html file using javascript to display the results of YQL Query.
I understand how to setup the select statement (example: select title,abstract,url from search.web where query="pizza") in the YQL Console. But I don't know how to display it on the html file?
Can somebody help in explaining how to display the results of that statement?
Code snippets would be appreciated!
BTW, I've read the YQL Docs but they are somewhat complicated.
The only way to retrieve YQL results via client-side JavaScript is JSON-P (or by using an additional proxy). Here's a wrapper for the YQL service:
function YQLQuery(query, callback) {
this.query = query;
this.callback = callback || function(){};
this.fetch = function() {
if (!this.query || !this.callback) {
throw new Error('YQLQuery.fetch(): Parameters may be undefined');
}
var scriptEl = document.createElement('script'),
uid = 'yql' + +new Date(),
encodedQuery = encodeURIComponent(this.query.toLowerCase()),
instance = this;
YQLQuery[uid] = function(json) {
instance.callback(json);
delete YQLQuery[uid];
document.body.removeChild(scriptEl);
};
scriptEl.src = 'http://query.yahooapis.com/v1/public/yql?q='
+ encodedQuery + '&format=json&callback=YQLQuery.' + uid;
document.body.appendChild(scriptEl);
};
}
Usage:
// Construct your query:
var query = "select * from rss where url='somefeed.com' limit 1";
// Define your callback:
var callback = function(data) {
var post = data.query.results.item;
alert(post.title);
};
// Instantiate with the query:
var firstFeedItem = new YQLQuery(query, callback);
// If you're ready then go:
firstFeedItem.fetch(); // Go!!
More info: http://james.padolsey.com/javascript/using-yql-with-jsonp/
Here is a small example for you. I made it using the YQL website:
<html>
<head>
</head>
<body>
<script>
function top_stories(o){
// parse through the output here:
var items = o.query.results.item;
// do whatever you want with the output here:
console.log(items[0].title);
}
</script>
<script src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&diagnostics=false&callback=top_stories'></script>
</body>
</html>
All it does it get the very first news story from Yahoo!'s front page

Categories