I am trying to get a very simple Stock API to work on JSFiddle.net using Quandl API: https://www.quandl.com/blog/api-for-stock-data
If I use the current ".csv" format as below, I am returned a CSV file. If I change the format to ".json" in my API, how do I recover the data so that I can use it on a website for example?
I believe I need to use a getJSON command, but I am confused as to how it works. Can someone help me out?
HTML:
<input type="text" id="symbol">
<button id="getPrice">Get Price!</button>
<div id="result">Stock Market Ticker</div>
JavaScript:
function getPrice() {
var symbol = $("#symbol").val();
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var stock = symbol+".csv";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var url = baseurl+ stock + "?" + endurl;
$("#result ").html("<a href = '" + url + "' >Hyperlink</a>");
}
$("#getPrice ").click(getPrice);
My OUTPUT using stock ticker KORS (.CSV file) is: Data Close
1/5/2016 40.72
I've recently answered to "How do I use a Quandl API?" with the following snippet, which you should adapt for your JSON:
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var quandlcode = "KORS"; // if is it's your choice?
var url = baseurl + quandlcode + ".json?" + endurl; // dont forget the "?"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
var data = JSON.parse(this.responseText).dataset.data;
// {}.dataset.data is the data matrix in Quandl
// for most datasets as far as I know ...
// then process your own way
}
xhr.send();
Related
When I put this into the browser, it brings back the json object just fine to me with all the weather data:
http://api.openweathermap.org/data/2.5/weather?zip=90210&units=imperial&appid={API Key}
However, I'm using my XAMPP Apache in the htdocs folder to try and test it out in my code. Can someone please look at my code and see what in the what is wrong here? Thank you so much for the help.
var weatherInfo = document.getElementById("weather");
var zipCodeForm = document.getElementById("zipCodeForm");
function getWeather(zipCode){
//create the url for the request
var endpoint = "http://api.openweathermap.org/data/2.5/weather";
var apiKey = {API Key};
var queryString = "zip=" + zipCode + "&units=imperial&appid=" + apiKey;
var url = endpoint + "?" +queryString;
//create the request to get the weather data
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", responseReceivedHandler);
xhr.requestType = "json";
xhr.open("GET", url);
xhr.send();
console.log("getWeather")
console.log(xhr.response.status);
}
function responseReceivedHandler(){
if(this.status === 200){
weatherInfo.innerHTML = "Current temperature: " + this.response.main.temp;
}
else{
weatherInfo.innerHTML="Not working";
}
console.log("responseReceivedHandler")
}
getWeather(90210);
<body>
<form id="zipCodeForm">
<label for="zipCode">Please enter your zip code: </label>
<input type="text" name="zipCode" id="zipCode">
<input type="submit" name="submit">
</form>
<div id="weather"></div>
</body>
HERE IS THE SOLUTION!!
My response needed to be converted from json to javascript object. It kept giving me undefined when I tried this.response.main.temp. The way I figured it out was the when I tried this.response[0], the result was a “{”. I was like, okay, so this must be unable to interpret this json as an object. It’s just a string of all the json characters. So I found json.parse() in order to turn it into a javascript object, and bam-- API ping success with the ability to access all the data.
Alternatively, you could just change "requestType = "json"" to responseType = json.... instead of having to parse it into an object. It's not requestType. It's responseType.
This is my jsp code. I want to bind the catid parameter to url when I call getproductsub() and send ajax request.
r.open("GET", "url?catid=" + catid,true);
above line seems an error of my code.How can I fix it.
<select class="form-control" id="pcategory" name="pcategory" onchange="getproductsub();">
<script>
function getproductsub() {
var catid = document.getElementById('pcategory').value;
var url = window.location.href;
var r = new XMLHttpRequest();
r.onreadystatechange = function() {
if (r.readyState === 4 && r.status === 200) {}
};
r.open("GET", "url?catid=" + catid, true);
r.send();
}
</script>
Note that window.location.href gives the complete location including the parameters in the url at the current time. So ? might be included in it.
You can either use
var url = window.document.location.pathname;
And concat the url to the String passed to open().
r.open("GET", url + "?catid=" + catid, true);
OR
Use getRequestURL() as you are coding in jsp.
r.open("GET", "<%= request.getRequestURL()%>?catid=" + catid, true);
I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});
Can anyone help me please?
I'm trying to create a record using the create method through javascript.
I need to copy all the fields' value and create a new entity. Like cloning a record in CRM 4.0
I'm using quote entity. I'm trying to pass the Opportunity. It was successful but when i look into the grid view, the opportunity field is blank. but in the form, it has a value.
Then i try to look into the opportunity form and see related Quotation, but it doesn't appear there.
Thank you for your reply. here's my code
>
var authenticationHeader = GenerateAuthenticationHeader();
var OpportunityID = crmForm.all.opportunityid.DataValue[0].id;
var varFields = "<opportunityid>"+ OpportunityID +"</opportunityid>"
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"+
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
authenticationHeader+
"<soap:Body>"+
"<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<entity xsi:type='quote'>"+
varFields +
"</entity>"+
"</Create>"+
"</soap:Body>"+
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Create");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result
var resultXml = xHReq.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
// Open new contact record if no errors.
else
{
var quoteid = resultXml.selectSingleNode("//CreateResult");
window.open("/sfa/quotes/edit.aspx?id={"+quoteid.nodeTypedValue+"}");
}
}
Kindly help me please.
I really need it badly.
Thank you very much.
I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.