how to print ipdata language name using javascript? - javascript

Hi guys I need to know how to print the language name in ipdata
I have this code at the bottom working well and the results appear correct but when I get the name of the language the results show the language name = undefined;
results
184.23.215.250
United States
<img src="https://ipdata.co/flags/us.png">
US
North America
Sonic Telecom LLC
undefined
my js vars is
var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages.name;
you can try it from http://tiger222.atwebpages.com/set.php
You will find the data correct but, how do I get the language name correctly ?
var lang = response.languages->name; this is not working
var lang = response.languages.name; and this is not working

In the source data, languages is an array, e.g.
"languages": [
{
"name": "English",
"native": "English"
}
],
Therefore it can potentially contain multiple entries.
Assuming you just want the first language in the list, then you can address the first index of the array directly, like this:
var lang = response.languages[0].name;
P.S. -> is not valid syntax in JavaScript. You were perhaps thinking of PHP syntax there.

This is array
var lang = response.languages[0].name;

Languages is an array so you would have to map on its elements and get name out of it.
"languages": [
{
"name": "English",
"native": "English"
}
],
It may break if there are no languages in the array so you can do defensive code like below:
var lang = (response.languages && response.languages.length && response.languages[0].name) || '';
const response = {
"ip": "12.00.00.01",
"is_eu": false,
"city": "Any City",
"region": "Pennsylvania",
"region_code": "PA",
"country_name": "United States",
"country_code": "US",
"continent_name": "North America",
"continent_code": "NA",
"latitude": 49.9776,
"longitude": -95.3099,
"asn": "AS7018",
"organisation": "AT&T Services, Inc.",
"postal": "18083",
"calling_code": "1",
"flag": "https://ipdata.co/flags/us.png",
"emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
"emoji_unicode": "U+1F1FA U+1F1F8",
"carrier": {
"name": "AT&T",
"mcc": "310",
"mnc": "016"
},
"languages": [
{
"name": "English",
"native": "English"
}
],
"currency": {
"name": "US Dollar",
"code": "USD",
"symbol": "$",
"native": "$",
"plural": "US dollars"
},
"time_zone": {
"name": "America/New_York",
"abbr": "EDT",
"offset": "-0400",
"is_dst": true,
"current_time": "2019-05-30T08:52:43.569643-04:00"
},
"threat": {
"is_tor": false,
"is_proxy": false,
"is_anonymous": false,
"is_known_attacker": false,
"is_known_abuser": false,
"is_threat": false,
"is_bogon": false
},
"count": "1501"
};
var country_name = response.country_name;
var flag = response.flag;
var country_code = response.country_code;
var continent_name = response.continent_name;
var organisation = response.organisation;
var lang = response.languages[0].name;
console.log(lang);

Related

how to GET and store specific values as a list from JSON data(URL) in javascript?

I tried several approches and none of them works. I think this is because I am using JSON returned by django DRF.
I want to create a list of IFSC using this JSON in Jquery in my HTML template itself.
This is how my api returns JSON for any queryset.
{
"count": 134,
"next": "http://127.0.0.1:8000/api/bankdetailapi/?limit=5&offset=5&q=ABHY",
"previous": null,
"results": [
{
"ifsc": "ABHY0065001",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "RTGS-HO",
"address": "ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065002",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "ABHYUDAYA NAGAR",
"address": "ABHYUDAYA EDUCATION SOCIETY, OPP. BLDG. NO. 18, ABHYUDAYA NAGAR, KALACHOWKY, MUMBAI - 400033",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065003",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "BAIL BAZAR",
"address": "KMSPM'S SCHOOL, WADIA ESTATE, BAIL BAZAR-KURLA(W), MUMBAI-400070",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
}
]
}
The code I tried:
$(document).ready(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = `IFSC: ${data.ifsc}`
})
)}
It throws error in browser console that Uncaught ReferenceError: text is not defined . I want to use this IFSC list as autocomplete suggestions.
$("#q").keyup(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = ['']
for (var i=0;i<data.results.length;++i){text.push(data.results[i].ifsc)}
// var text = `IFSC: ${data.results.ifsc}`
console.log(text)
By using push method and iterating on whole data i managed to get list of all IFSC values.

How do I update the shipping options at checkout in BigCommerce

I've written a custom app which uses a PHP server for the back end and the bigcommerce checkout/cart sdk with JS for the front end.
Basically this is what I want to do:
Retrieve Rates using my php app and a 3rd party api (This works)
Display said rates as selectable options (This works)
Update the checkout and consignment (This works but not 100%)
Update the cart shipping method and total (This is where I am stuck)
After I get the rates from the PHP server, I dynamically build the list's HTML.
I randomly assign shipping method id's (As I have no idea how this gets generated but it appears to be fairly random)
When I click on a shipping option this code runs (Please note that 'option' is a variable within a foreach loop
console.dir(checkoutObj);
if(checkoutObj.consignments.length < 1){
console.log('no consign');
} else {
var selectedShipping = checkoutObj.consignments[0].selectedShippingOption;
selectedShipping.cost = parseFloat(option['grandtotmrkup']);
selectedShipping.description = option['CarrierName'] + '-' + option['CarrierService'];
selectedShipping.id = this.value;
selectedShipping.type = 'weight_based_shipping';
checkoutObj.consignments[0].shippingCost = parseFloat(option['grandtotmrkup']);
checkoutObj.shippingCostBeforeDiscount = parseFloat(option['grandtotmrkup']);
checkoutObj.shippingCostTotal = parseFloat(option['grandtotmrkup']);
console.log('updated checkout obj');
console.dir(checkoutObj);
var updated = service.updateCheckout(checkoutObj);
console.log('updated');
console.dir(state.data.getCheckout());
console.log('updating consignment');
console.dir(
service.updateConsignment({'id':consignID,'shippingOptionId':shippingMethodId})
);
console.dir(state.data.getConsignments());
When it runs service.updateConsignment I get the following response for the consignments section of the object:
"consignments": [
{
"id": "5f732875d039f",
"shippingCost": 0,
"handlingCost": 0,
"couponDiscounts": [],
"discounts": [],
"lineItemIds": [
"4f557702-4f9d-45ec-943a-c72ea963ccc7"
],
"selectedShippingOption": {
"id": "4dcbf24f457dd67d5f89bcf374e0bc9b",
"type": "freeshipping",
"description": "Free Shipping",
"imageUrl": "",
"cost": 0,
"transitTime": "",
"additionalDescription": ""
},
"shippingAddress": {
"firstName": "1",
"lastName": "1",
"email": "",
"company": "",
"address1": "1 street",
"address2": "",
"city": "MITCHAM",
"stateOrProvince": "Victoria",
"stateOrProvinceCode": "VIC",
"country": "Australia",
"countryCode": "AU",
"postalCode": "3132",
"phone": "",
"customFields": [],
"shouldSaveAddress": true
},
"availableShippingOptions": [
{
"id": "9ba45e71fe66e1cd757f022dcae331b0",
"type": "shipping_pickupinstore",
"description": "Pickup In Store",
"imageUrl": "",
"cost": 0,
"transitTime": "",
"isRecommended": false,
"additionalDescription": ""
},
{
"id": "4dcbf24f457dd67d5f89bcf374e0bc9b",
"type": "freeshipping",
"description": "Free Shipping",
"imageUrl": "",
"cost": 0,
"transitTime": "",
"isRecommended": true,
"additionalDescription": ""
}
]
}
],
I'm not sure if it's because my shipping options aren't in the Available Shipping Options Section of the object?
Does anyone know how I can get my shipping methods in there? Or is this being caused because I append the methods dyanmically via HTML?
I'm new to BC so please excuse any ignorance.
I don't think you're going to be able to inject a shipping option into the checkout this way, I think you'd need to look at using the Shipping Methods API in your PHP app and then the options should be available as per usual.

Get object from an array inside of an array

I am trying to get a list of places from Foursquare's API. So far so good, but I have hit a wall that I can't figure out. Hopefully someone on here might have a good idea.
The list I currently have shows the types of venues from a forsquare list, and then it breaks down each venue's name and lat/lng. The issue that I am having is getting the category from foursquare. The category is stored inside of another array, inside of the array for the venue.
Here is what I have so far:
function app(info) {
$('#content').append(info);
}
function getinfo(venueAPI) {
$.getJSON(venueAPI, function (data) {
var arr = [];
var venuearr = [];
$('#content').empty();
console.log(data);
b = '<br/>';
categoryArr = data.response.list.categories.items;
categoryArrLength = data.response.list.categories.items.length;
console.log(categoryArr);
console.log(categoryArrLength);
for (var x = 0; x < categoryArrLength; x++) {
app(categoryArr[x].category.pluralName + b);
}
arr = data.response.list.listItems;
venuearr = arr.items;
console.log(venuearr);
for (var i = 0; i < venuearr.length; i++) {
ltlng = L.latLng(venuearr[i].venue.location.lat, venuearr[i].venue.location.lng);
$('#content').append(ltlng + b);
app(venuearr[i].venue.name + b);
}
});
getinfo();
}
which returns JSON like this for each venue:
"venue": {
"id": "51db2eca498e76d75a5dfea2",
"name": "A Gathering Of Stitches",
"contact": {},
"location": {
"address": "54 Cove St",
"lat": 43.66797,
"lng": -70.256453,
"cc": "US",
"city": "Portland",
"state": "ME",
"country": "United States",
"formattedAddress": [
"54 Cove St",
"Portland, ME"
]
},
"categories": [
{
"id": "4bf58dd8d48988d1f4941735",
"name": "Design Studio",
"pluralName": "Design Studios",
"shortName": "Design",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/shops/design_",
"suffix": ".png"
},
"primary": true
}
],
and this is what get's printed out on the screen:
Pubs
Thrift / Vintage Stores
Design Studios
Coffee Shops
LatLng(43.6565, -70.25313)
Bull Feeney's
LatLng(43.65697, -70.25081)
Andy's Old Port Pub
LatLng(43.6571, -70.25713)
Arabica Coffee
LatLng(43.66797, -70.25645)
A Gathering Of Stitches
LatLng(43.65687, -70.25763)
Find
I've tried several different ideas, but nothing has seemed to work so far.
venue.categories[0].name;
fiddle:
http://jsfiddle.net/18kfrek5/

Setting 3rd Level Nested Attribute on a Backbone Model

I'm having trouble changing the location $id on this Backbone model.
{
"approved": null,
"caption": "This is my photo!",
"created": 1393537913,
"location": {
"_id": {
"$id": 5
},
"address1": "155 West Street",
"city": "Bangkok",
"country": "THA",
"latitude": "13.136",
"longitude": "100.2068",
"postalCode": "10330",
"region": "AP"
}
}
I've tried:
model.set({"location":{"_id":{"$id": 6}}})
But that obviously overwrites the entire location object.
model.set({"location._id":{"$id":6}})
Creates a new attribute on the model, "location._id".
So, how can I dig in to the location to change that attribute?
You can do like this :
var location = model.get('location');
location._id = { "$id": 6 };

How to use JSON Stringify when fields are own object types?

EDIT: Something like this, but this is not working either, but there is the problem I think
var stringifyObj = JSON.stringify({
"addressAddressId":$('#address').val(){
"cityId:"$('#city').val(){
"postalCode":$('#postalCode').val()
}
}
});
*When I generate test client in Netbeans, JSON-structure (GET/JSON) is like that, but how can I code that with Javascipt and Strinfy-function? *
"addressAddressId": {
"addressId": 1,
"address": "Järnvägen 2",
"address2": null,
"district": null,
"postalCode": "20360",
"phone": null,
"coordinates": null,
"latitude": null,
"longitude": null,
"directions": null,
"description": null,
"addrZipCityCountry": null,
"lastUpdated": 1361754860000,
"cityId": {
"cityId": 1,
"city": "",
"lastUpdate": 1361754850000,
"countryCountryId": {
"countryId": 1,
"country": "Sweden",
"lastUpdate": 1361754837000
}
}
},
QUESTION
What is the correct syntax when using JSON.stringify in case of own
object type like City-object inside of Address-object?
Should I add every field to json if not using
#JsonIgnoreProperties({""})? I just need address, city and postal
code. address is type of Address with field String address in server
side, City is type of City includes String-field for city name etc.
I'm not sure what are you trying to do with your Javascript function above, but if your goal is to produce JSON with such structure using Javascript, maybe you can try this :
var stringifyObj = JSON.stringify({
"addressAddressId": {
"addressId": 1,
"address": "Järnvägen 2",
"address2": null,
"district": null,
"postalCode": "20360",
"phone": null,
"coordinates": null,
"latitude": null,
"longitude": null,
"directions": null,
"description": null,
"addrZipCityCountry": null,
"lastUpdated": 1361754860000,
"cityId": {
"cityId": 1,
"city": "",
"lastUpdate": 1361754850000,
"countryCountryId": {
"countryId": 1,
"country": "Sweden",
"lastUpdate": 1361754837000
}
}
}
});
Basically, all you need to do is wrap the JSON string as a parameter for the JSON.stringify.
Or, if you need to build the object incrementally, instead of providing all the properties at once like above, maybe you can try this :
var obj = {};
//add properties as needed
//simple properties
obj.addressId = 1;
obj.address = "Järnvägen 2";
obj.address2 = null;
//nested properties
obj.cityId = {};
obj.cityId.cityId = 1;
obj.cityId.countryCountryId = {};
obj.cityId.countryCountryId.countryId = 1;
After all the object properties are properly filled, pass it to the JSON.stringify like this :
var stringifyObj = JSON.stringify(obj);
Or, to produce the JSON described on your example, you can further wrap the obj like this :
var stringifyObj = JSON.stringify({ addressAddressId = obj });
I hope you get the idea :)
And you are missing a comma here, though I can't say that is your issue.
"postalCode": {
"postalCode": $('#postalCode').val()
} <--- need comma here
"addressAddressId": {

Categories