Get selected json value by key using jQuery and jsonp (vimeo api) - javascript

Let's say I have the following json result from an api:
{
id: 116213129,
title: "“An Episode,” by Palaxy Tracks",
description: "Music: Palaxy Tracks<br /> Animation: Luca Tóth and Stephen McNally",
url: "http://vimeo.com/116213129",
thumbnail_small: "http://i.vimeocdn.com/video/502490003_100x75.jpg",
thumbnail_medium: "http://i.vimeocdn.com/video/502490003_200x150.jpg",
thumbnail_large: "http://i.vimeocdn.com/video/502490003_640.jpg",
user_id: 14252792,
width: 1920,
height: 1080,
tags: "palaxy tracks, music, an episode, animation, music video"
}
Now let's say I have some jQuery code and I want to only retrieve title and url, but nothing else and do something with them like push them into the value of a textbox on my page or a hidden input. I have seen the $.each method that loops through them, but I don't wt to do that. I just want a few values and I want to get them by their key.
Here is the sample jQuery code that loops through them, I got from jQuery API docs. How can I modify to just get those specific values?
<script>
$.getJSON("http://vimeo.com/api/v2/video/116213129.json?jsoncallback=?", function (result) {
var title = result.title;
var description = result.description;
$("#popVals").click(function () {
$('#Video_Title').val(title);
$('#Video_Description').val(description);
});
});
</script>

From the JQuery.getJSON docs:
The success callback is passed the returned data, which is typically a
JavaScript object or array as defined by the JSON structure and parsed
using the $.parseJSON() method. It is also passed the text status of
the response.
In your case its a Javascript object which will be accessible via property access
<script>
$.getJSON("http://vimeo.com/api/v2/video/116213129.json?jsoncallback=?", function (result) {
var title = result.title;
var url = result.url;
//do something
});
</script>

Related

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

Append data in JSON format

I have some data in JSON format. I want to display it on a div. Following doesn't work. Any idea where i should change.
<div class="risktable"> </div>
$.ajax({
contentType:'application/json',
data: {"sprint_start":"2015-12-13","sprint_end":"N.A.","available":[{"id":5,"name":"Thisun H","free_time":0.0,"possible":[]}],"assigns":[{"assignee_id":6,"assigned_to":"Isuru P","status":"OnTrack","hours_per_sprint":6,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":3,"task_name":"Schedule Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Isuru P","estimated_time":6,"remaining_time":6,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":7,"assigned_to":"Manoj D","status":"Risk","hours_per_sprint":6,"limit_per_sprint":5.0,"limit_per_day":5.0,"tasks":[{"task_id":4,"task_name":"Resource Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Manoj D","estimated_time":6,"remaining_time":0,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":5,"assigned_to":"Thisun H","status":"OnTrack","hours_per_sprint":0,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":1,"task_name":"Redmine Connection","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":3,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-07","due_date":"2015-12-09","critical_task":true,"dependents":[2,3,4]},{"task_id":2,"task_name":"Risk Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":10,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-10","due_date":"2015-12-12","critical_task":false,"dependents":[]}]}],"suggestions":[{"dev_id":5,"dev_name":"Thisun H","task_id":4,"task_name":"Resource Servlet"}]},
success: function(data){
$.each(data.data, function(i,value) {
$('.risktable').append(
'<div>'+'<p>'+ value.assigns.assignee_id + '</p>'
+'</div>'
);
});
}
});
assigns property on your json object is an array. you need to loop through the items in that and build your div and append that.
$.each(data.assigns, function(i,value) {
var item='<div>'+'<p>'+ value.assignee_id + '</p></div>';
$('.risktable').append(item);
});
Here is a working sample.
If the json data you have isn't being fetched externally (i.e. you have the json object definition & value already), there's no need to do the ajax method call. Ajax is used for making external requests.
Alternatively, you could store your json object as a generic variable and parse through it (assuming you are using jQuery) like the following.
var mock_data = {"sprint_start": "2015-12-13","sprint_end":"N.A.","available": [{"id":5,"name":"Thisun H","free_time":0.0,"possible":[]}],"assigns":[{"assignee_id":6,"assigned_to":"Isuru P","status":"OnTrack","hours_per_sprint":6,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":3,"task_name":"Schedule Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Isuru P","estimated_time":6,"remaining_time":6,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":7,"assigned_to":"Manoj D","status":"Risk","hours_per_sprint":6,"limit_per_sprint":5.0,"limit_per_day":5.0,"tasks":[{"task_id":4,"task_name":"Resource Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Manoj D","estimated_time":6,"remaining_time":0,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":5,"assigned_to":"Thisun H","status":"OnTrack","hours_per_sprint":0,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":1,"task_name":"Redmine Connection","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":3,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-07","due_date":"2015-12-09","critical_task":true,"dependents":[2,3,4]},{"task_id":2,"task_name":"Risk Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":10,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-10","due_date":"2015-12-12","critical_task":false,"dependents":[]}]}],"suggestions":[{"dev_id":5,"dev_name":"Thisun H","task_id":4,"task_name":"Resource Servlet"}]};
$(mock_data.assigns).each( function(){
$('.risktable').append('<div><p>'+this.assignee_id+'</p></div>');
});
You can see the sample here:
http://codepen.io/team/anthro-web/pen/yeYobN

How to check if a ResultSet of an AJAX call using JQuery has value

I am Using iQuery to make AJAX Calls to the server and return a set of values. The Values returned are dynamic. The Result count being dynamic I am not able to look the result set and assign values to HTML Elements to show in Web Page.
Kindly advice how I could look if there is a value in the result set and use the same in my system. The Maximum count in result set is 16 and i have manually assigned values in the Script.
Calling the AJAX Method in the document ready of my Web Page.
$(document).ready(function () {
CallAJAX('../Forms/Send.aspx/refreshDash', '', 'FillMethod', 'FillMethodE');
});
AJAX Call Definition
function CallAJAX(ServerMethod, Parameters, SuccessMethod, ErrorMethod) {
$.ajax({
type: "POST",
url: ServerMethod,
data: Parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, errorThrown) {
Error = xhr; Result.d.ResultSet[0].TRCOUNT
eval(ErrorMethod + "()");
},
success: function (msg) {
Result = msg;
var rr = SuccessMethod + "();";
eval(rr);
}
});
}
Using Two jQuery Functions to Show Details and prompt Message when error is Raised. Note Error Function is not Shown.
function FillMethod() {
if ($.isEmptyObject(Result.d.ResultSet)) {
}
else {
$('[id$=lblCode1]').html(Result.d.ResultSet[0].DASH_NAME);
$('[id$=lblNot1]').html(Result.d.ResultSet[0].TRCOUNT);
$('[id$=lblCode2]').html(Result.d.ResultSet[1].DASH_NAME);
$('[id$=lblNot2]').html(Result.d.ResultSet[1].TRCOUNT);
$('[id$=lblCode3]').html(Result.d.ResultSet[2].DASH_NAME);
$('[id$=lblNot3]').html(Result.d.ResultSet[2].TRCOUNT);
$('[id$=lblCode4]').html(Result.d.ResultSet[3].DASH_NAME);
$('[id$=lblNot4]').html(Result.d.ResultSet[3].TRCOUNT);
$('[id$=lblCode5]').html(Result.d.ResultSet[4].DASH_NAME);
$('[id$=lblNot5]').html(Result.d.ResultSet[4].TRCOUNT);
$('[id$=lblCode6]').html(Result.d.ResultSet[5].DASH_NAME);
$('[id$=lblNot6]').html(Result.d.ResultSet[5].TRCOUNT);
$('[id$=lblCode7]').html(Result.d.ResultSet[6].DASH_NAME);
$('[id$=lblNot7]').html(Result.d.ResultSet[6].TRCOUNT);
$('[id$=lblCode8]').html(Result.d.ResultSet[7].DASH_NAME);
$('[id$=lblNot8]').html(Result.d.ResultSet[7].TRCOUNT);
$('[id$=lblCode9]').html(Result.d.ResultSet[8].DASH_NAME);
$('[id$=lblNot9]').html(Result.d.ResultSet[8].TRCOUNT);
$('[id$=lblCode10]').html(Result.d.ResultSet[9].DASH_NAME);
$('[id$=lblNot10]').html(Result.d.ResultSet[9].TRCOUNT);
$('[id$=lblCode11]').html(Result.d.ResultSet[10].DASH_NAME);
$('[id$=lblNot11]').html(Result.d.ResultSet[10].TRCOUNT);
$('[id$=lblCode12]').html(Result.d.ResultSet[11].DASH_NAME);
$('[id$=lblNot12]').html(Result.d.ResultSet[11].TRCOUNT);
$('[id$=lblCode13]').html(Result.d.ResultSet[12].DASH_NAME);
$('[id$=lblNot13]').html(Result.d.ResultSet[12].TRCOUNT);
$('[id$=lblCode14]').html(Result.d.ResultSet[13].DASH_NAME);
$('[id$=lblNot14]').html(Result.d.ResultSet[13].TRCOUNT);
$('[id$=lblCode15]').html(Result.d.ResultSet[14].DASH_NAME);
$('[id$=lblNot15]').html(Result.d.ResultSet[14].TRCOUNT);
$('[id$=lblCode16]').html(Result.d.ResultSet[15].DASH_NAME);
$('[id$=lblNot16]').html(Result.d.ResultSet[15].TRCOUNT);
}
};
function FillMethodE() {
}
Issue is being raised in the FillMethod function when only Result.d.ResultSet[0].DASH_NAME has a valid value and the following indexes does not have any values.
NOTE: Results are returned in pairs, if DASH_NAME is available then TRCOUNT will also be available for the same index.
All I need to do is irrespective of the result count i need to display in the labels in order values from the result set dynamically. Here are are two sets of result sets which could be obtained.
I'm afraid it's still really, really unclear what the specific problem is (and the sample result sets you posted don't provide any clarity on why you can't simply loop over them), but I'm willing to take a guess...
Is the problem that you're trying to write a dynamic set of results to a static set of placeholders for the output?
If that's the case, don't make the placeholders static. Just keep an empty space where you want the results to show and when you have the results, write them to that part of the page. You don't need HTML elements in place already, you can create them dynamically. For example:
success: function (msg) {
// let's assume msg is an array of data
for(var i = 0; i < msg.lengh; i++) {
$('#output').append(
'<div>' + msg[i].DASH_NAME + ' - ' + msg[i].DASHSTATUS + '</div>'
);
}
}
So if your #output is just a div, the result would look like this:
<div id="output">
<div>SEND CONFIRMED - 1</div>
<div>RECV HO RESPONDED - 4</div>
<div>RECV HO PAID - 3</div>
<!-- etc... -->
</div>
How you define and style that markup is entirely up to you, of course. The point is that you can create the markup on the fly from your JavaScript code, so it can be created dynamically based on the results from the AJAX request.
Try this
if (Result.d.ResultSet.length > 0) {
for (i = 0; i < Result.d.ResultSet.length; i++) {
$('[id$=lblCode'+i+']').html(Result.d.ResultSet[i].DASH_NAME);
$('[id$=lblNot1'+i+']').html(Result.d.ResultSet[i].TRCOUNT);
}

How to render HTML with jQuery from an AJAX call

I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html

How to put alert value to element

in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element
you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);
try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.

Categories

Resources