output has multiple id's and i need 1 id - javascript

i got a json fetcher and its working fine. but when i need an ID. it sends out all the id's that are in the json.
i need only the latest one, could that be possible?
Its the first time that i am working on json so i am currently noob in it.
$(document).ready(function() {
// FETCHING DATA FROM JSON FILE
$.getJSON("https://api.omny.fm/orgs/56ccbbb7-0ff7-4482-9d99-a88800f49f6c/programs/a49c87f6-d567-4189-8692-a8e2009eaf86/clips/",function(data) {
$('#table').html(data.Clips.map(studentData => `${studentData.Id}`).join(''));
});
});
added [:1] and [0] but that didn't work sadly

you can do it using [0] accessor
also I added ?pageSize=1 to the url so it just download one record
$(document).ready(function() {
// FETCHING DATA FROM JSON FILE
$.getJSON("https://api.omny.fm/orgs/56ccbbb7-0ff7-4482-9d99-a88800f49f6c/programs/a49c87f6-d567-4189-8692-a8e2009eaf86/clips/?pageSize=1",function(data) {
$('#table').html(data.Clips[0].Id);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div>

Related

How to set a specific json response object as a js var - Cloudinary

I am using Cloudinary to host my profile images that are set by users.
I'm mostly using PHP for my web application -> Here are the instructions as provided by Cloudinary http://cloudinary.com/documentation/php_image_upload#overview
The problem that I encounter is that I want to display the image directly after upload by parsing the newly created URL for the image that is returned by JSON.
When I do the console.log as provided by Cloudinary:
$(document).ready(function() {
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
console.log(data);
return true;
});
});
This is the console.log response that I receive
Can anyone please help me with a javascript or JQuery function that I can use in order to display the updated image with in my image tag.
You need read the tree...
jqXHR.responseJSON.url
In this case, use
data.result.url
See example of http://cloudinary.com/documentation/php_image_upload#preview_thumbnail_progress_indication_multiple_images
Can you update the src of your image tag based on the json returned?
Something like this in the callback function:
var imgDiv = document.getElementById("profile");
imgDiv.src = data.jqXHR.responseJSON.url;

Showing results from JSON only when filter is selected

Objective
I want display results only when it's respective state is selected. Currently all results are shown by default when the page loads.
I do not want anything to load by default. When a state is selected then those results should populate.
Background
I have a location selection feature that I am working on at this CodePen.
It used MustacheJS for templating
and is populated by data in a JSON file by this script
$(function() {
$.getJSON('https://s3-us-west-2.amazonaws.com/s.cdpn.io/161741/labs.js', function(data) {
var template = $('#labsListStates').html();
var html = Mustache.to_html(template, data);
$('#states').html(html);
});
});
The results can be filtered by state with. It runs on this script
/* Filter for locations */
$('#lab-state-select').on('change', function (e) {
e.preventDefault();
var cat = $(this).val();
var nam = $(this).val();
$('#states > div').hide();
$('#states > div[data-category-type="'+cat+'"][data-category-name="'+nam+'"]').show();
});
Problems
I know that this is sloppy. I am not using pure JSON but actually creating a Javascript object. And even named the file to end with .js so that it would work. I read about how that is a bad practice at http://www.kryptonite-dove.com/blog/load-json-file-locally-using-pure-javascript
That taught me to look into a XMLHttpRequest. But even implementing that I am still confused how to display the data I need when I need it. I think I am on the correct track by looking into the
.on() but would appreciate some additional help.
You simply use $('#states > div').hide(); to hide the data right after you load the data: $('#states').html(html);.
You can check out the fork here: http://codepen.io/anon/pen/lBims
As for getting the JSON file, you can simply return it with any file type. You don't have to use a .js extension if it's just pure JSON output. And JSON is just a stringified representation for Javascript objects, so it's fine treating JSON as an object. In Fact that's what you're supposed to do. JSON = JavaScript Object Notation.

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Reading contents from a JSON url and writing out those contents

I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});

Displaying data from a database using jQuery and Javascript

I'm trying to display specific parts of a Cloudant database. This database contains many separate documents, and each document contains a category called "results". I'm trying to display whatever is in results. Each document is identified by its own id. I tried using the get() method in jQuery, but unfortunately it is not running successfully.
function grabData(){
var url = 'https://cloudant.com/futon/document.html?acharya%2Ftoxtweet/ff558f75077e8c758523cd3bd8ffdf88';
$.get(url, function(data) {
$('.result').html(data);
alert("Data loaded: " + data);
});
}
grabData();
I'm not entirely sure where I went wrong...Should I consider using SQL instead of ajax?
I think your issue it this:
replace this:
grabData();
with this:
$(document).ready(function(){
grabData();
});
or more shortened:
$(function(){
grabData();
});
The URL you are using is returning an entire webpage.
Your jQuery code is looking for an element on the current page with a class name of result and trying to change it's inner HTML to the response from the URL.
You didn't provide any additional code to look at, but I would assume that is not what you were expecting it to do.
I assume you are wanting to parse through the entire url, but in your current code the page will be processed as a raw string and not a DOM object. So you would have to parse through that string with regular expressions, etc.

Categories

Resources