AJAX & Json get function with jQuery - javascript

I am creating a "Garment checker" using ajax and I would like the user to put the ID into the input followed by a request to the URL. which prints out the code if it exists. The code below just isn't doing the job as I would like it to although I think that it is almost correct. Can anybody see my mistakes or point me in the right direction please?
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
"use strict";
$('#lookupForm')
.removeAttr('onsubmit')
.submit(function(event) {
event.preventDefault();
var target = document.getElementById('garmentID');
if(target.value.length > 0) {
fetchData(target.value);
}
});
});
function fetchData(garmentID) {
var url = 'http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=' + applicationID;
$.getJSON(url, function(data) {
var appDetails = data.AvailableSkus[0];
$('#garmentTitle').val(appDetails.AvailableSkus);
});
}
//]]>
</script>

Since data.AvailableSkus seems to be an array, you don't want to pass the collection as the value to #garmentTitle.
You're most likely after a property (if the array contains objects) or the actual element:
//if typeof appDetails.AvailableSkus[0] is string or number:
$('#garmentTitle').val(appDetails.AvailableSkus[0]);
or
//if typeof appDetails.AvailableSkus[0] is an object:
$('#garmentTitle').val(appDetails.AvailableSkus[0].someProp);
value
Type: String or Array
A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.

This link provides output properly
http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=5
are you sure "applicationID" is setted before ?
var url = 'http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=' + applicationID;
Any error message in firebug console ?

Related

Complex JSON obj and jQuery or Javascript map to specific key, value

I am banging my head trying to figure this out. And it should not be this hard. I am obviously missing a step.
I am pulling data from: openaq.org
The object I get back is based on a JSON object.
For now, I am using jQuery to parse the object and I am getting to the sub portion of the object that hold the specific parameter I want but I can't get to the specific key,value pair.
The object does not come back in the same order all the time. So when I tried to originally set up my call I did something like
obj.results.measurements[0].
Well since the obj can come back in an random order, I went back to find the key,value pair again and it was the wrong value, throwing my visual off.
That said, I have looked at use jQuery's find() on JSON object and for some reason can not get what I need from the object I am given by openaq.org.
One version of the object looks like this:
{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
I am trying to get the "pm25" value.
The code I have tried is this:
function getAirQualityJson(){
$.ajax({
url: 'https://api.openaq.org/v2/latest?coordinates=39.73915,-104.9847',
type: 'GET',
dataType: "json"
// data: data ,
}).done(function(json){
console.log("the json is" + JSON.stringify(json));
console.log("the json internal is" + JSON.stringify(json.results));
var obj = json.results;
var pm25 = "";
//console.log(JSON.stringify(json.results.measurements[0]["parameter"]));
$.each(json.results[0], function(i,items){
//console.log("obj item:" + JSON.stringify(obj[0].measurements));
$.each(obj[0].measurements, function(y,things){
//console.log("each measurement:" + JSON.stringify(obj[0].measurements[0].value));//get each measurement
//pm 2.5
//Can come back in random order, get value from the key "pm25"
// pm25 = JSON.stringify(obj[0].measurements[2].value);
pm25 = JSON.stringify(obj[0].measurements[0].value);
console.log("pm25 is: " + pm25); // not right
});
});
//Trying Grep and map below too. Not working
jQuery.map(obj, function(objThing)
{ console.log("map it 1:" + JSON.stringify(objThing.measurements.parameter));
if(objThing.measurements.parameter === "pm25"){
// return objThing; // or return obj.name, whatever.
console.log("map it:" + objThing);
}else{
console.log("in else for pm25 map");
}
});
jQuery.grep(obj, function(otherObj) {
//return otherObj.parameter === "pm25";
console.log("Grep it" + otherObj.measurements.parameter === "pm25");
});
});
}
getAirQualityJson();
https://jsfiddle.net/7quL0asz/
The loop is running through I as you can see I tried [2] which was the original placement of the 'pm25' value but then it switched up it's spot to the 3rd or 4th spot, so it is unpredictable.
I tried jQuery Grep and Map but it came back undefined or false.
So my question is, how would I parse this to get the 'pm25' key,value. After that, I can get the rest if I need them.
Thank you in advance for all the help.
You can use array#find and optional chaining to do this,
because we are using optional chaining, undefined will be returned if a property is missing.
Demo:
let data = {"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
let found = data?.results?.[0]?.measurements?.find?.(
({ parameter }) => parameter === "pm25"
);
console.log(found);
You can iterate over measurements and find the object you need:
const data = '{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}';
const json = JSON.parse(data);
let value = null;
const measurements = json?.results?.[0]?.measurements ?? null;
if(measurements)
for (const item of measurements)
if (item.parameter === 'pm25') {
value = item.value;
break;
}
if (value) {
// here you can use the value
console.log(value);
}
else {
// here you should handle the case where 'pm25' is not found
}

Replacing values in JSON object

I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.

Using string variable as a json object name

I have a dynamic string variable created by UI (valkey in below code) and I want to use that variable as a JSON key to get a value from TestObj which is a JSON object. But an attempt with the following code has returned an error.
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL")
{
$.each(TestObj.valkey, function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}
I appreciate any help.
TestObj.valkey will look for the key valkey in TestObj, which is undefined in your case that is why you are getting the error.
If you want to look for a key from a variable you need to use the syntax TestObj[valkey].
Ex:
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL") {
$.each(TestObj[valkey], function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}

Javascript Object literal, POST problems

Im trying to get autocomplete-rails.js working in Rails with Ajax,
i Have the following function
<script type="text/javascript">
function reply_click(clicked_id)
{
var x = "work";
var y = "monday"
alert(y)
$.ajax({
type : 'POST',
url : "/whens",
data: { y : x},
success : function(data) {
alert(data);
},
});
}
</script>
The problem im getting is that this returns
"y"=>"work"
and i want it to return the value of y instead
"monday"=>"work"
Also, if i do the following
<script type="text/javascript">
function reply_click(clicked_id)
{
var x = "work";
var y = "monday"
var data = {};
data[x] = y;
$.ajax({
type : 'POST',
url : "/whens",
data,
success : function(data) {
alert(data);
},
});
}
</script>
it seems to return The problem im getting is that this returns
"term"=>"work"
Any idea how i can get it returning the contents of y
If a key doesn't have quotes, that doesn't mean it's using a variable.
The correct way of doing it, as you mention is
var data = {};
data[y] = x;
$.ajax({
type : 'POST',
url : "/whens",
data : data,
success : function(data) {
alert(data);
},
});
Note I changed it to data[y] = x;
if u want to load some data using ajax which in return can be used for auto-complete then load the array of strings by ajax.
eg.
in controller do-
def get_characteristics
unless ['Threads', 'Note'].include?(params[:name])
#characteristics = Category.all.collect(&:characteristic)
respond_to do |format|
format.js{}
end
end
in get_characteristics.js.haml (eg is in haml)
var characteristics = #{#characteristics.to_json};
$('#characteristic').autocomplete( //the id of the text fields where u want autocomplete
source: characteristics //the array of string that u want for autocomplete
)
for additional info http://jqueryui.com/demos/autocomplete/
variable as index in an associative array - Javascript
> var x = "work"
> var y = "monday"
> data= {}
{}
> data[x]=y
'monday'
> data
{ work: 'monday' }
You can't, the second snippet (data[y] =) is the only way. Here's why:
An object literal, like all things in JS is an object (duh) and has properties. All variables declared in the global scope are properties of the global (nameless) object. The only (semi-)true variables you have are the ones you declare in a closure scope. So looking at it from that viewpoint, it stands to reason that properties should not be quoted when constructing an object literal. I'd even go as far as to say that allowing quoted properties in the declaration of an object literal should be considered wrong, or it should -at the very least- be discouraged.
JS is a wonderful language, covered up by a pile of inconsistencies, quirks and bad ideas. Sadly, if all you know is the gunk (almost everybody knows the gunk, few know the actual language and where it gets its power) the rare features that are consistent and good look like an obstacle at first. Thankfully, you have tons of constructs that enable you to do just what you want, and do it well.
In this case, you could just write it all out data[a] = b; data[c] = d;... OR you could use a power-constructor (google it)
An other option is just a very small loop, assuming your data object will be filled using the arguments passed to the function:
var data = {};
var argArray = Array.prototype.slice.apply(arguments,[0]);//returns array of arguments
var duo;
while(duo = argArray.splice(0,2))
{
data[duo[0]] = duo[1];
if (argArray.length < 2)
{
break;
}
}
just to give an example. I'd recommend you (and everyone else) to look into crockfords constructions when it comes to objects, and what a function call entails in JS: a function isn't just called, a call-object is created.

Javascript split is not a function

Hey friends i am using javascript sdk to post on users friends wall with jQuery facebook multi friend selector however i am getting this error friendId.split is not a function. Here is my code
function recommendToFriend(pic, url, friendId, fromName)
{
alert(friendId);
var friendList ;
pFriend = new Array();
pFriend = friendId.split(',');
for( x in pFriend )
{
alert(pFriend[x]);
var publish = {
method:'feed',
picture:pic,
link:url,
name:'SHARP Product Recommend',
caption: fromName + 'has recommend a product to you via Sharp Expert lounge',
};
FB.api('/'+pFriend[x]+'/feed', 'post', publish, function(resp) {
if( !response || response.error )
alert('Unable to share');
else
alert('Successfully posted to firends wall');
});
}
}
In alert box i got comma seperated friend ids so i use split function post on each users wall seperately i dont know whats wrong here please help me
Most probably friendID is already an array. If you call alert the array is converted to a string and becomes a comma separated list of values.
Note that converting an array to a string is not the same as calling JSON.stringify (where you get also brackets and double quotes around elements when they're strings)
The JavaScript split() function is for the type string ie for eg.
var friendid='1,34,67';
As VisioN says, when you alert an array you get comma separated values.
You can traverse JS Objects like this
for (var key in friendid) {
var obj = friendid[key];
for (var prop in obj) {
alert(prop + " = " + obj[prop]);
}
}
Hope this helps
alternate
for( var x in friendId )
{
alert(friendId[x]); // this would be your desired value
}

Categories