I recently came across the Yify-torrents api at YifyTorrentAPI and just thought let's give it a try with jquery and create a little own application. I used the following code to retrieve the upcomming movies list which worked.
$.getJSON("https://yts.re/api/upcoming.json", function(data) {
$.each(data, function(item, value) {
console.log(value.MovieTitle + ' ' + value.ImdbLink);
});
});
on the other side when I tried to get all the movies list using the following request I just got undefined in the console.
$.getJSON("https://yts.re/api/list.json", function (data) {
$.each(data, function (item, value) {
console.log(value.MovieTitleClean + ' ' + value.ImdbLink);
});
});
I am sharing the Fiddle in which I have wrote the code. Any help will be appreciated. Thanks
The second ajax call is returning movies in a MoviesList object so you need to iterate on data.MovieList not data.
JSON:
{
"MovieCount":4921,
"MovieList":
[{
"MovieID":"5372",
"State":"OK",
"MovieUrl":"https:\/\/yts.re\/movie\/Gun_Woman_2014_1080p",
"MovieTitle":"Gun Woman (2014) 1080p","MovieTitleClean":"Gun Woman",
"MovieYear":"2014",
"DateUploaded":"2014-06-30 00:10:03",
"DateUploadedEpoch":1404043803,
"Quality":"1080p",
"CoverImage":"https:\/\/static.yts.re\/attachments\/Gun_Woman_2014_1080p\/poster_med.jpg",
"ImdbCode":"tt3141912",
"ImdbLink":"http:\/\/www.imdb.com\/title\/tt3141912\/",
"Size":"1.24 GB",
"SizeByte":"1335275815",
"MovieRating":"8.2",
"Genre":"Action",
"Uploader":"OTTO",
"UploaderUID":"310615",
"Downloaded":"35173",
"TorrentSeeds":"20",
"TorrentPeers":"24497",
"TorrentUrl":"https:\/\/yts.re\/download\/start\/777FD07DAD285CB06846CAFD97600B07F2CC88B3.torrent",
"TorrentHash":"777fd07dad285cb06846cafd97600b07f2cc88b3",
"TorrentMagnetUrl":"magnet:?xt=urn:btih:777fd07dad285cb06846cafd97600b07f2cc88b3&dn=Gun+Woman&tr=http:\/\/exodus.desync.com:6969\/announce&tr=udp:\/\/tracker.openbittorrent.com:80\/announce&tr=udp:\/\/open.demonii.com:1337\/announce&tr=udp:\/\/exodus.desync.com:6969\/announce&tr=udp:\/\/tracker.yify-torrents.com\/announce"
}]
}
do like this:
$.getJSON("https://yts.re/api/list.json", function (data) {
console.log("Getting all the movies");
// console.log(data)
$.each(data.MovieList, function (item, value) {
console.log(value.MovieTitleClean + ' ' + value.ImdbLink);
});
});
UPDATED FIDDLE
Related
Haven't touched Javascript for a bit while and cannot find a proper way to extract data from a JSON object.
So I am basically sending a simple GET request to the Giphy API and attempting to get URL's from the response but for some reason I get all kinds of errors.
This is what I tried:
$(function() {
$('#searchButton').click(function() {
console.log("test");
$("#result").append("test<br />");
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function(data) {
console.log(this.fixed_height);
$("#result").append("success got data<br />" + data + "<br />");
console.log("success got data", data);
$.each(data.results, function() {
$.each(this.images, function() {
console.log(this.fixed_height);
$("#result").append(this.fixed_height + "<br />");
});
})
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="searchButton">search!</button>
<div id="result"></div>
You have a couple of problems. First, there is not a results member in the data object. The only thing I see that you can iterate on, in the data object is yet another data member. Second, inside the images, there is no fixed_height, just height. This works:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
$.each(this.images, function () {
console.log(this.height);
});
})
});
http://jsfiddle.net/n9ffva83/
Remember $(function () {});is not needed in JSFiddle, so you must provided (just the way you do in the code you gave us above).
EDIT:
To just get the url of the fixed height try this:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
console.log(this.images.fixed_height.url);
})
});
It seems this url is only one, that belong to the images.
http://jsfiddle.net/n9ffva83/1/
I was wondering if someone could help me understand how to access data in my json doc.
[
{
"article":"title",
"img_thumb":"images/image.png",
"article_content":"This is content",
"alt":["keyword", "keyword2"]
},
{
//here's article 2
}
]
When document.ready, I'm executing this function, which works perfectly:
var article_populate = function(){
$.getJSON('json/test.json', function(data){
$.each(data, function(key, val){
var article = "<div class='thumb'><img src='" + val.img_thumb + "' class='img_thumb'><div class='div_btn article' id='" + val.article + "'>" + val.article + "</div></div>";
$('#srch_rslt').append(article);
});
})
}
Then if the user clicks on the article title, I want to append the article content from json to the div where the article title is.
Update: this is working now.
$('#srch_rslt').on('click', '.article_title', function(){
var get_article = $(this).attr('id');
console.log(get_article);
$.getJSON('json/test.json', function(data){
$.each(data, function(key, val){
if(val.article_id == get_article){
console.log(val.article_content)
$('#' + get_article).parent().append(val.article_content);
}
});
});
});
It looks like you are using $.getJSON incorrectly in your second example, whereas you are using it correctly in the first. Compare
$.getJSON('json/test.json', function(data, key, val){
versus
$.getJSON('json/test.json', function(data){
$.each(data, function(key, val){
Edit in response to edit of original question:
You will need to do something like this:
$('#srch_rslt').on('click', '.article_title', function(){
var get_article = $(this).attr('id');
console.log(get_article);
var article = $(this);
$.getJSON('json/test.json', function(data){
$.each(data, function(key, val){
if(val.article_id == get_article){
console.log(val.article_content)
article.parent().append(val.article_content);
}
});
});
});
Again, as mentioned in the comments, I recommend reading up on how this works in JavaScript.
You shouldn't use the article.title as an id since it can have illegal characters (',", à, é....).
Since your data structure is an array you can get to the data using the index of the clicked article:
var articleIndex = $(this).index();
with this you can get the corresponding data from your json:
var articleData = data[articleIndex]
Now you can append the article content:
$('selector_where_you_want_data').append(articleData.article_content);
The quick and dirty way is:
$('selector_where_you_want_data').append(data[$(this).index()].article_content);
val is an array with multiple articles right?
so it seems logical that your call gives undefined for val.article
i your json file article is not the lowest level so it should be something like
val.0.article.search(get_article)
val.1.article.search(get_article)
I'd suggest dumping the content of var to console using console.log(var); to see how to access the data correctly or if the data is loaded properly.
I have a list of items obtained upon querying a database. Result of the query is treated with jsonifyand finally obtained via getJson, by doing the following:
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output="<ul>";
for (var i in data.appts) {
output+="<li>" + data.appts[i].labo + "</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
});
So far so good...
Now I need to give the possibility to delete each of the above listed items, by calling (for example ) the following Flaskfunction:
#app.route('/appointments/<int:appointment_id>/delete/', methods=['DELETE'])
def appointment_delete(appointment_id):
appt = db.session.query(Appointment).get(appointment_id)
db.session.delete(appt)
db.session.commit()
return jsonify({'status': 'OK'})
Unfortunately I have no clue on how it's possible to bridge these two pieces of code. Since I've being struggling on that for a while, I would appreciate any help that will allow me to get out of the mud... Thanks a lot.!
EDIT according to #dcodesmith's comment
The getJSON response:
{
"appts":[
{
"id":1,
"day":"Mardi",
"labo":"l1",
"modified":[
"21/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"28/01/2014"
]
},
{
"id":4,
"day":"Vendredi",
"labo":"l1",
"modified":[
"22/01/2014"
],
"groups":"5",
"plage_h":"10h00",
"sem":"5",
"start":[
"31/01/2014"
]
}
]
}
Changes required
Firstly, edit your output HTML to include an anchor tag which should have a data-id attribute with the appts id assigned to it.
Create a click event on the anchor tag in your list of appts
Code
$(function() {
$.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
var output = "<ul>";
for (var i in data.appts) {
var appt = data.appts[i];
output += "<li>" + appt.labo + "delete</li>"
}
output+="</ul>";
$("#result").html(output)
return false;
});
$(document).on('click', 'a.delete', deleteAppt);
function deleteAppt(e){
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
url = "/appointments/" + id + "/delete/";
$.ajax({
url: url,
type: 'POST',
data: {id: id}
})
.done(function(data, textStatus, jqXHR){
if (data.status === 'OK'){
// if successful remove deleted row
$this.parent('li').remove();
}
})
.fail(function(jqXHR, textStatus, errorThrown){
//log your error here, if any is caught. This will be very helpful for debugging
})
}
});
Note: I know nothing about Flask, but this should work Ceteris Paribus
I want to send json data from my controller to my view when a specific action happens.
I used this on controller to send the data
[HttpGet]
public JsonResult JSONGetParking(int buildingID){
return this.Json(
new
{
Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
}
, JsonRequestBehavior.AllowGet
);
}
it works very good
on my script i used this:
FloorScript.js
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
I have opened google chrome and I can see the request and the response like this:
i can see the two text that i alerted
However, on my selector, i just see undefined value
Html
<div id="editor-label">
<select id="parkingID" name="parkingID"></select>
</div>
I have added the jquery in this
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/FloorScript.js");
}
You're not looping on the correct variable.
You did this:
$.each(data, function (obx, oby) {
whereas you should do this:
$.each(data.Result, function (obx, oby) {
This is pretty visible in the Google Chrome screenshot you provided. As you can see the returned JSON has a property called Result which is the collection whereas you were looping over the data variable which is not an array - it's just a javascript object that has a property called Result which is the array you wanna be looping through.
Also I'd replace:
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
with:
$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {
and of course get rid of this hardcoded url over there and use an url helper to generate it, on the dropdown as an HTML5 data-* attribute:
#Html.DropDownListFor(
x => x.BuildingId,
Model.Buildings,
new {
id = "buildingID",
data_url = Url.Action("JSONGetParking")
}
)
and then inside the change event you can trivially easy retrieve this url and avoid hardcoding it (and of course taking the risk of breaking your code when you deploy it in IIS in a virtual directory or simply change the routing pattern of your application):
$('#buildingID').change(function () {
var url = $(this).data('url');
$.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {
Alright, now the initial mess is tidied up.
use data.Result in your each loop
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data.Result, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
Hope this helps...
Here is the code I'm attempting to use (parts pulled from remote json, parts removed from the custom data display):
$(function () {
$("#Field1Text").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/Main/Users/GetItems",
dataType: "json",
data: {
group: "Default",
query: request.term
}
},
focus: function (event, ui) {
$("#Field1Text").val(ui.item.Description);
return false;
},
select: function (event, ui) {
$("#Field1Text").val(ui.item.Description);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.Description + "</strong><br>" + item.Section + " - " + item.Type + " - " + item.Name + "</a>")
.appendTo(ul);
};
});
The data pulls back fine, but the render item function never fires. I've scrapped the render item version and used success: inside of source and it looked like this:
success: function (data) {
response($.map(data, function (ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.Description + "</strong><br>" + item.Section + " - " + item.Type + " - " + item.Name + "</a>")
.appendTo(ul);
}));
}
I used firebug and I was able to hit a breakpoint at the response section: if I looked at the data in data, it looked like:
[ Object { ...data... }, Object { ...data... }]
If I set a breakpoint at the .data line of the success section, I see that ul is one of the objects ( looks like " Object { ... data ... }")
the item element is 0 at this point, and when I attempt to render the <a> tags, it comes out as Undefined on all of the properties (understandable, looks to be treating the item object as an int).
How do I get that component to handle properly?
edit: sorry, I wanted to add a jsFiddle per the suggestion in the comments but had family stuff going on.
http://jsfiddle.net/EYj8v/2/
I commented the code that is similar to what we use at work. Unfortunately, the web app is an internal one with a database that isn't connected to the outside world so I can't use live data. The testResults object is what I saw in the success: section's data element.
I was actually able to get the success section to fire, but I don't believe I'm using jQuery UI/Autocomplete correctly (at least my assumptions) as I was able to look at ul.Properties and see real data. Appending the items worked with bogus data, but when I attempted to copy and paste the success block into the render item, all of the data was undefined. Nor could I find a one-to-one mapping at that stage (ul was the element on the page, item was just [li]).