I'm attempting to make a Pebble app that reads data from a JSON URL.
However, no matter what I do I can't seem to make the data appear on the app.
When entering this code in:
console.log(data.contents.AvailableBal);
console.log(data.contents.CurrentBal);
I would expect to get a result back in the logs that would help but I only get:
[PHONE] pebble-app.js:?: None
[PHONE] pebble-app.js:?: None
And when viewing the app in the emulator, both values where the data should be, say "Undefined".
My code is as follows. Any help would be great!
var UI = require('ui');
var ajax = require('ajax');
var splashCard = new UI.Card({
title: "Please Wait",
body: "Downloading..."
});
splashCard.show();
ajax(
{
url: 'https://djkhaled.xyz/balance.json',
type: 'json'
},
function(data) {
console.log(data.contents.AvailableBal);
console.log(data.contents.CurrentBal);
var main = new UI.Card({
title: 'Balances',
body: 'Available Balance: ' + data.contents.AvailableBal +
'\nCurrent Balance: ' + data.contents.CurrentBal
});
splashCard.hide();
main.show();
}
);
This is your JSON,
{
"contents": [{
"AvailableBal": "$0.00 CR",
"CurrentBal": "$0.00 CR"
}]
}
You can not directly access data.contents.AvailableBal because AvailableBal is not directly inside contents. contents has an array
and this array's first object (object at index 0) contains the object that has AvailableBal and CurrentBal keys.
I'm not a JavaScript developer but probably answer would be something like this,
var main = new UI.Card({
title: 'Balances',
body: 'Available Balance: ' + data.contents[0].AvailableBal +
'\nCurrent Balance: ' + data.contents[0].CurrentBal
});
Related
I was using this code below to get the title/artist data from an old-station (https://stream.mydnic.be/status-json.xsl) with ajax:
(function worker() {
$.ajax({
url: host + '/status-json.xsl',
success: function(data) {
artist = data.icestats.source.artist;
title = artist + ' - ' + data.icestats.source.title;
document.title = title;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});
Now I changed the station and the new one use another JSON file that looks a little different:
"id": "station_name",
"songs":[
{
"title": "Water Silence",
"artist": "Solar Fields",
"album": "Fahrenheit Project Part Five",
"albumart": "",
"date": "1569618168"
},
The problem is that now, I get 'undefined' on Title and artist with the first Ajax Code.
So, I would like to ask if someone knows what I need to change on the first ajax code to work with the new JSON file and get the title/artist data correctly.
I really appreciate your help.
You are trying to get an attribute from an object when it is a list of objects, what you have to do is iterate the array or get the result by index.
Like this:
(function worker() {
$.ajax({
url: host + '/status-json.xsl',
success: function(data) {
//In this example you getting element by index
artist = data.songs[0].artist;
title = data.songs[0].title;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});
I tried to get a random Wikipedia page over their API via Google Cloud Functions. The Wikipedia API works fine. This is my request:
https://de.wikipedia.org/w/api.php?action=query&format=json&generator=random
For testing you can change the format to jsonfm in see the result in the browser. Click here 👍.
But it seems that my functions get destroyed even before the request was completely successfully. If I want to parse the data (or even if I want to log that data) I got a
SyntaxError: Unexpected end of json
The log look like (for example) that (no I haven't cut it by myself):
DATA: ue||"},"query":{"pages":{"2855038":{"pageid":2855038,"ns":0,"title":"Thomas Fischer
Of course, that is not a valid json and can't be parsed. Whatever this is my function:
exports.randomWikiPage = function getRandomWikiPage (req, res) {
const httpsOptions = {
host: "de.wikipedia.org",
path: "/w/api.php?action=query&format=json&generator=random"
};
const https = require('https');
https.request(httpsOptions, function(httpsRes) {
console.log('STATUS: ' + httpsRes.statusCode)
console.log('HEADERS: ' + JSON.stringify(httpsRes.headers))
httpsRes.setEncoding('utf8')
httpsRes.on('data', function (data) {
console.log("DATA: " + data)
const wikiResponse = JSON.parse(data);
const title = wikiResponse.query.title
res.status(200).json({"title": title})
});
}).end();
};
I've already tried to return something here. Like that video explained. But as I look into the node docs https.request don't return a Promise. So return that is wrong. I've also tried to extract the on('data', callback) into it's own function so that I can return the callback. But I haven't a success with that either.
How have to look my function that it return my expected:
{"title": "A random Wikipedia Page title"}
?
I believe your json comes through as a stream in chunks. You're attempting to parse the first data chunk that comes back. Try something like:
https.request(httpsOptions, function(httpsRes) {
console.log('STATUS: ' + httpsRes.statusCode)
console.log('HEADERS: ' + JSON.stringify(httpsRes.headers))
httpsRes.setEncoding('utf8')
let wikiResponseData = '';
httpsRes.on('data', function (data) {
wikiResponseData += data;
});
httpRes.on('end', function() {
const wikiResponse = JSON.parse(wikiResponseData)
const title = wikiResponse.query.title
res.status(200).json({"title": title})
})
}).end();
};
I'm trying to add a folder to a document library using REST in a SharePoint 2013 SharePoint hosted app. It is hosted in an Office 365 developer site. I'm following the guidelines in MSDN here as well as using the excellent samples on dev.office.com (especially the REST Helper).
While capturing the request during debugging I can't see any problems with my request compared to the documentation and samples. I haven't had issues with any GET requests either.
Here is my request:
var datatext = "{'__metadata': {'type': 'SP.Folder'}, 'ServerRelativeUrl': '" + serverRelativeUrl + foldername + "'}";
$.ajax({
url : $appweburl + "/_api/web/folders",
type: "POST",
data: datatext,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-type": "application/json;odata=verbose",
"content-length": datatext.length
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
This generates an error "value does not fall within the expected range"
So this uses "data" instead of "body" because "body" was always generating a JSON Reader error. All of the samples indicate "body" but I found other sources that show this key should be "data" in a POST like this, and it resolves the JSON reader error. I ensure that ServerRelativeUrl leads with a "/" as well as filename.
Any help is greatly appreciated.
EDIT: To follow up on this, I was successful using JSOM only. It turns out that you must add a ListItem to the list and specify the content type to be a folder to achieve this. It works, but it makes me wonder if you have to do something similar in REST - that is rather than use the folder endpoints, do it like adding a listitem to a list. I have not confirmed it.
Usually the error Value does not fall within the expected range occurs since ServerRelativeUrl property was specified in incorrect format.
The following formats are supported:
[Document Library]/[New Folder] list/library relative url
/[Site]/[Web]/[Document Library]/[New Folder] - site collection
relative url
http(s)://[Server]/[Site]/[Web]/[Document Library]/[New Folder]
absolute url
How to create a Folder using SharePoint 2013 REST
Assume the following site structure:
`News` site (under `sites` managed path)
|
`Documents` library
|
`Archive` folder
Then the following examples demonstrate how to create a folder named 2010 in Documents library:
Example 1
createFolder(_spPageContextInfo.webAbsoluteUrl,'/sites/news/Documents/Archive/2011')
.done(function(data)
{
var folder = data.d;
console.log('Folder ' + folder.Name + ' has been created successfully');
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
Example 2
createFolder(_spPageContextInfo.webAbsoluteUrl,'Documents/Archive/2010')
.done(function(data)
{
var folder = data.d;
console.log('Folder ' + folder.Name + ' has been created successfully');
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
where
function executeRequest(url,method,headers,payload)
{
if (typeof headers == 'undefined' || headers == null){
headers = {};
}
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
function createFolder(webUrl,folderUrl)
{
var url = webUrl + "/_api/web/folders";
var folderPayload = { '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': folderUrl};
return executeRequest(url,'POST',null,folderPayload);
}
I have refered many questions on stack overflow and on other sites for the solution. But everywhere I got incomplete answer. some answer says log the json data to console. So I tried it and there I get the json object correctly. But when I add it to HTML or alert it says [object Object].
There are many duplicates of this question but still I dont understand what the problem is?
Here is my code so far
$(document).click(function () {
$.ajax({
type: "POST",
url: "/members/ListOfAllOppositeTypeUsersWithTheirRespectiveData?LoggedInUserOppositeType=2",
dataType: 'json',
success: function (json) {
console.log(json);
//var strJson = JSON.stringify(json);
$.each(json, function (key, value) {
$('#AllowedFriends').append($('<option value="'+ key + '">' + value + '</option>'));
});
},
error: function () {
alert("F");
}
});
});
edit :
The values that I get in the console :
0: Object
MemberID: 1
Name: "Cipla"
1: Object
MemberID: 2
Name: "Himalaya"
You should try something like:
$.each(json, function (index, obj) {
$('#AllowedFriends').append($('<option value="'+ obj.MemberId + '">' + obj.Name + '</option>'));
});
An object can contain actual data, what is the problem? I suggest you take a look at the network calls from your browser using the developer console or Firebug to see what object is received. Then jQuery parses the string into an object so you can use the data.
Try console.log(eval('('+json+')'));
I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});