This is my API call:
https://itunes.apple.com/search?term=cut+the+cord&limit=1
I only want to get the value of the '"releaseDate":"2015-06-29' part.
Is there any way that I could only get that part in a textbox. I have this textbox in another page. Any ideas or suggestions?
Due to the cross-domaine policy, you must use JSONP to get json data and then format response value:
$.ajax({
url: "http://itunes.apple.com/search?term=cut+the+cord&limit=1",
dataType: "jsonp",
success: function( response ) {
console.log( response );
var d = new Date(response.results[0].releaseDate);
var y = d.getFullYear();
var m = pad( d.getMonth()+1, 2);
var d = pad( d.getDate(), 2);
$("#release").attr('value', y + "-" + m + "-" + d)
}
});
http://jsfiddle.net/yts728L5/2/
I guess you're parsing your result as JSON:
var result = JSON.parse(apiCallResult)
Then, assuming you only have one result as in the example request above, you should be able to get that value by simply accessing the object:
var results = result.results;
var releaseDate = results[0].releaseDate;
This will work if you have multiple results also, but it will only take the first result's releaseDate.
To add the text to a text box, you can use jQuery to get the text box and then set its value:
var textBox = $("#myTextBoxId");
textBox.val(releaseDate);
Related
the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.
I've gotten this from the forum already, but one of the answers provided a way to use search parameters in a url string. Some of my tables are too big to load in a browser, so apparently I will have to find out how to add search parameters to this code. The only reason I didn't use the other code was that it showed how to do that with a calendar.
I know nothing about JSON/jQuery/razor/c#. Please help.
#{
var db = Database.Open("LGOnline");
var result = db.Query("SELECT * FROM CashOS");
var data = result.Select(x => new
{
ID = x.ID,
STORE_NO = x.STORE_NO,
DATE = x.DATE,
MWS_AMOUNT = x.MWS_AMOUNT,
FINAL_AMOUNT = x.FINAL_AMOUNT
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
Update: I am using Microsoft WebMatrix 3. I am able to get the data from my tables with this code and it converts them to JSON. I just don't need all of it at once.
Update: I got it to do what I was trying to do. It isn't pretty, and I am open for any number of suggestions, but this made it to where I can type in the url and add &STORE_NO=55 and also i can select a date if I want to.
#{
var db1 = Database.Open("LGOnline");
var formValue2 = Request.Form["STORE_NO"];
var formValue3 = Request.Form["DATE"];
if (IsPost)
{
Response.Redirect("test.cshtml?&STORE_NO=" + formValue2 + "&DATE=" + formValue3);
}
var Keyword2 = Request.QueryString["STORE_NO"]; //Retrieves passed variable from the database search page for STORE_NO
var Keyword3 = Request.QueryString["DATE"]; //Retrieves passed variable from the database search page for DATE
var sqlQ = "SELECT * FROM CashOS WHERE STORE_NO LIKE #0 AND DATE LIKE #1";
var dataQ = db1.Query(sqlQ, "%" + Keyword2 + "%", "%" + Keyword3 + "%");
var requestedData = dataQ.Select(x => new
{
ID = x.ID,
STORE_NO = x.STORE_NO,
DATE = x.DATE,
MWS_AMOUNT = x.MWS_AMOUNT,
FINAL_AMOUNT = x.FINAL_AMOUNT
}).ToArray();
Json.Write(dataQ, Response.Output);
Response.ContentType = "application/json";
}
This is the output by the way:
[{"ID":28,"STORE_NO":55,"DATE":"/Date(1442811600000)/","MWS_AMOUNT":10.1600,"FINAL_AMOUNT":10.1600}]
Thank You all for your help!!
I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}
Objective: To collect JSON data from forecast API and then read the JSON precipIntensity property over the number of days specified, this code starts at three. Since this take a number of steps to coherently follow please try to make sense of all the code.
My main issue is trying to name the JSON code pages that return then put them into another context to read the precipIntensity
property.
To outline: The back date gets the UNIX time, then requests an API for each forecast day. Then the APIs are put in an array. The array is put in a for() loop to request each JSON script... (now what to do? I would like to be able to read each or calculate something but I do not know how to ask for the formatted code. I can do the remaining bit).
A sample of JSON can be found at my other related post...
https://stackoverflow.com/questions/29949454/store-json-api-object-data-and-reuse-it (I found that the API server stores the data for me...solved)
EDITED since 5/1/15:
//Get the back dated times and current in UNIX,
//later make a lookup that gives datediff from current date and user's date and adjust index i condition to equal exact days.
var totalPrecipSinceDate;
var threeDayAPITimes = [];
for (var i = 0; i <= 2; i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //https://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime(); //1318023197289 number of ms since epoch
var unixEpoch = Math.round(epoch/1000)
threeDayAPITimes[i] = Math.round(unixEpoch - (86400 * i));
/*
var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
threeDayAPITimes[i] = Math.round(epoch - (86400 * i));
*/
}
//Plan to convert UNIX dates to display
//List of locations: LATITUDE,LONGITUDE
var locations = ["46.3494,-85.5083"]
var currentAPIKey ="privateAPIKey"; //gets an APIkey from user from forecaster input.
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
});
//Process result in foreach loop
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (this.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ;
});
}
alert(eachPrecipSum );
Your loop should be something like this:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time;
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
});
}
I have a Python script that returns me a calculated date time in XML format like below:
<prev><date>2012,07,16</date><time>22:00:00</time></prev>
Though I can change the format but my issue is that when I try creating a JS date object using the value returned - I get 'Invalid date':
$.ajax({
async: false,
type: "POST",
url: "/cgi-bin/prev_hour.py",
success: function(xml)
{
pdate = $(xml).find('date').text();
ptime = $(xml).find('time').text();
//alert prints correct date time ex 2012-07-16 22:00:00
},
error:function(xhr,err,html)
{
alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
}
var max_date = new Date("'" + pdate + ptime + "'");
alert(max_date);
I tried a couple of possibilities like Python script returning in various format:
<prev><date>2012/07/16 </date><time>22:00:00</time></prev>
<prev><date>2012,07,16 </date><time>22,00,00</time></prev>
But still I get invalid date when trying to create a JS date object?
Please let me know the correct way to implement it.
You don't need the extra set of quotes in your date string, and you will need a space between the date and time components, try:
new Date(pdate + " " + ptime);
Try using amazing lib for dates called Moment.js
moment("2012/07/16 22:00:00")
from there you can achieve everything with dates.
This:
var max_date = new Date("'" + pdate + ptime + "'");
Should be:
var max_date = new Date(pdate + ' ' + ptime);
Next time you run into such issues put an alert on the value you are sending to the function and see what it looks like.