I am using the weatherunderground api, and I would like to access the forecast only for today. I usually use parsed_json[][] until I get the variable I need, but in this case there is an array. Here is my code:
function findWeather() {
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/c531e176f43b999d/forecast/q/CT/Old_Greenwich.json",
dataType : "jsonp",
success : function(parsed_json) {
var forecasts = parsed_json['forecast']['txt_forecast']['forecastday: 0']['fcttext'];
var forecastString = "The weather is" + forecasts + "."
speak(" test" + forecastString);
}
});
});
}
function speak(x) {
var msg = new SpeechSynthesisUtterance(x);
window.speechSynthesis.speak(msg);
}
If you go to the URL, you will see the entire sheet and the info I am trying to access. I've been trying to solve this for a few hours, and can't find any help with google.
Try this:
parsed_json['forecast']['txt_forecast']['forecastday'][0]['fcttext'];
Don't know what you expect the :0 to do, but it won't de-reference the array.
Related
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");
}
I would really appreciate some help on this. I have a page that shows products in a store using laravel pagination. I have filters on the page based on brands, category, and available products. for filtering the products I am using a checkbox. if a checkbox is checked I use ajax get request and send status via URL to a controller to filter available products.
status = 1 is for available products, and status = 0 is for all products.Url is looks like this:
/Collections/Newest_Items?status=1&page=2
Here is the situation. I want to know if is it possible to change the variable value in URL and regenerate the URL base on the page number and new filters dynamically? Is it a way to get the URL of the page using jquery and change the values and then change the Url with window.history.pushState("", "", URL);?
Here is my ajax:
$(document).on('click', "#only_available", function () {
if ($('#only_available').is(':checked')) {
var status = 1;
url = '/Collections/Newest_Items?status='+status;
} else {
var status = 0;
url = '/Collections/Newest_Items';
}
window.history.pushState("", "", url);
$.ajax({
url: '/Collections/Newest_Items',
type: "GET",
data: {status: status},
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
});
I do this by writing the URL by myself. In this situation, I must write the URL after every filter applied to the page. this way I cant get the page the user currently in and it goes back to the first page. But what I want to achieve here is, I want to make the Url dynamically with page number the user currently on with all filters applied to it.
You can use window.location.search which will give you something like: status=1&page=2 in your example. Then you will need to parse out those variables to get the page number you're looking for.
Ok I think I understand what you are asking for. So with each unique filter event that you are firing you need to query the current url before pushstate and get the values with something like this.
For instance if someone clicks Brand then you would get the new brand variable as well as the current status and page variables to pass with ajax like this
also just POST it instead of GET
$(document).on('click', ".brand", function () {
var brand = $(this).attr('id);
//Example how to use it:
var params = parseQueryString();
var status = params["status"]);
var page = params["page"]);
// if you have more variables than this then you would add them here and make sure you pass them along to the ajax data.
url = '/Collections/Newest_Items?status='+status+'&page='+page+'&brand='+brand;
window.history.pushState("", "", url);
$.ajax({
url: '/Collections/Newest_Items',
type: "POST",
data: {status: status, page: page, brand: brand},
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
var parseQueryString = function() {
var str = window.location.search;
var objURL = {};
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
return objURL;
};
tnx to #CesarBielich and #Sokies I finally manage to solve the problem. they give me part of the answer but not all.I made it unique to my question:
what we need here is the path and the parameters that nested in URL. so for getting the path of the route, we must use window.location.pathname and for getting all the parameters must use window.location.search. after that, we must combine the path and params so that the URL comes out of it. then we must add the new parameter like status after that. So that all the parameters can be accessed by the controller. both the old params and the new one. this way laravel pagination knows what url to make, in the href links to other pages.
$(document).on('click', "#only_available", function () {
if ($('#only_available').is(':checked')) {
var status = 1;
} else {
var status = 0;
}
var params = window.location.search;
var path = window.location.pathname;
var old_url = path+params;
var url = old_url+'&status=' + status;
window.history.pushState("", "", url);
$.ajax({
url: url,
type: "GET",
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
});
I have the following JSON data from my API
[{"email":"user#gmail.com","status":"Active"}]
This is the JS/jQuery code I am using to get the data
function formLogin() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var dataString = "email=" + email + "&password=" + password;
jQuery.ajax({
url: "http://localhost/OnlineShop/API/fetch_user_login_api.php",
data: dataString,
type: "POST",
success: function(data) {
$("#login-form").html(data);
console.log('success');
//window.location.href = "store.html?shopper=";
var obj = jQuery.parseJSON(data);
alert(obj.email);
},
error: function() {
console.log('error');
}
});
return true;
}
alert(obj.email) is throwing undefined. How do I retrieve the email and status from the JSON result?
Your "data" variable is already an object or an array, you don't need to call parseJSON.
Then, it seems that your object is an Array of objects
This should work:
alert(data[0].email);
I advice you to check if your array is empty or not before calling this line.
The API returns [{"email":"user#gmail.com","status":"Active"}] as it is of type Array.
first you need to take the first element of the Array by obj = obj[0].
then it is something like {"email":"user#gmail.com","status":"Active"}.
now you can get the email element by simply obj["email"]
if you call your api and get the result like this:
[{"email":"user#gmail.com","status":"Active"}]
it's an array, what you can do to fix the error is:
1) change your api response structure to JSON not array
2) use for to iterate your response
And I advice you next time, you have this kind of error, just console.log the raw data to find what's the structure of it, and you'll have the solution.
I'm trying to add both Facebook and Twitter share counters together, however all my efforts have failed.
<script>
tweets = 0;
function getTwitterCount(url){
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
return true;
});
}
var urlBase='http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: function(data) {
showCount(data);
}
});
var fbshares = 0;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
}
var TotalShares = tweets + fbshares;
$('#total-share-count').html(TotalShares);
</script>
I could really do with some outside insight as I've been working crazy to get this website up and running ASAP and I'm probably overlooking the most obvious of things...
Console Log Reads:
Uncaught ReferenceError: fbshares is not defined
sdk.js:64 Invalid App Id: Must be a number or numeric string representing the application id.
card.html?v=2:79 Uncaught ReferenceError: I18n is not defined
sdk.js:64 FB.getLoginStatus() called before calling FB.init().
However despite this message, the Facebook and Twitter counters are working 100%, I just cannot get them to add together.
Best Regards,
Tim
Here's a solution:
var tweets;
function getTwitterCount(url) {
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data) {
tweets = data.count;
$('#twitterCount').html(tweets);
showTotal();
});
}
var urlBase = 'http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: showCount
});
var fbshares;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
showTotal();
}
function showTotal() {
if (tweets !== undefined && fbshares !== undefined)
$('#total-share-count').html(tweets + fbshares);
}
Basically showTotal attempts to sum the two values after each callback. When both values are defined, it will place the sum into the HTML.
I have the following function:
function updateproductselectionxxx(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
var target = 'productselectionresult' + productassignment;
var myAjax = new Ajax.Updater(target, checkingurl, {
method: 'post',
parameters: pars
});
}
And I am currently in the process of converting all the javascript on this website to jQuery. Usually I can use something similar to:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
$.ajax({
type: 'POST',
url: 'shopajaxproductselection.asp',
data: $(form).serialize(),
success: function (response) {
$(form).find('productselectionresult' + productassignment).html(response);
}
});
return false;
}
And that does the trick, however I really only want to send over 1 field as indicated in the first function and I would also like to send along the information I am sending directly to the function upon it being called. JavaScript is definitely not my area of expertise but usually I can muddle through, but this time everything I have tried has caused errors and I'm not getting very far. Any help would be greatly appreciated.
Looks like a bit of confusion between POST and GET. Although the request method is set to POST in the older Prototype version the params are being sent via CGI which normally appear on the server as a GET. It's a bit hard to say more without seeing the server-side code, but you could try this, such that the jQuery version more closely mimics the old Prototype version:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
$.ajax({
type: 'POST',
url: url,
data: {},
success: function (response) {
$(form).find('#productselectionresult' + productassignment).html(response);
}
});
return false;
}
Note that I have added a hash # to the start of productselectionresult - this is crucial due to the difference in the way PrototypeJS works. In Prototype, you can use an ID selector like:
$('id')
whereas in jQuery it has to be:
$('#id')