Why am i receiving error 404 when fetching video data? - javascript

I'm trying to display the video which is in mp4 format of the code's folder. When i try to fetch the video by clicking on the button it shows an empty space but doesn't display the video.display of the output
The error i'm receiving from the console: GET http://127.0.0.1:8080/myapi/myapi1/undefined 404 (Not Found)
Below is the url to display the json data:
http://localhost:8080/myapi/myapi1/user/1
The link above displays:
{"videoName":"video.mp4"}
The code to fetch the video and display using ajax:
$('#room1').on('click',function (e){
$.ajax({
method: "GET",
cache: false,
dataType: "json",
url: "http://localhost:8080/myapi/myapi1/user/1",
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
value.videoName + '" autoplay loop muted></video>';
});
$('#video').append(student);
},
error:function(exception){alert('Exeption:'+exception);}
})
e.preventDefault();
});

So, The data you are fetching is in JSON ENCODED FORMAT. so you need to parse it to a JS Object. like this: data = JSON.parse(data) in your success function.

(1) Since you only have one data item returned, please change the success block from:
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
value.videoName + '" autoplay loop muted></video>';
});
$('#video').append(student);
},
to
success: function(data) {
var student = '';
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
data.videoName + '" autoplay loop muted></video>';
$('#video').append(student);
},
data.videoName is already the data (video filename) you need
(2) However, if you have multiple data, like the following:
[{"videoName":"video.mp4"}, {"videoName":"video1.mp4"}]
then you may use the following :
success: function(data) {
var student = '';
for (var x = 0; x < data.length; x++) {
// DATA FROM JSON OBJECT
student += '<video height="603"';
student += 'src="' +
data[x].videoName + '" autoplay loop muted></video>';
}
$('#video').append(student);
},
data[index].videoName will be the data (video file name) for each index
(3) If you still prefer to use key / value pairs, the correct syntax will be like:
$.each(data, function (key, value) {
alert(data[key].videoName);
})

Related

How to iterate through json arrays

I'm stuck in a script here, not sure how to get it to print in the div I set up. I imagine it's something related to how I'm handling the response.
The response in chrome devtools looks like this:
{
"[\"record one\", \"/description\"]": 0
}
I've attempted to use both each and map to iterate the data out but so far not going anywhere. I'm brand new to js and jquery, so the script is mostly from reading and examples.
Maybe some kind of nested loop? Here is my code -
$(function() {
return $('#myslider').slider({
range: true,
min: 0,
max: 20,
values: [1, 20],
stop: function(event, ui) {
var max, min;
min = ui.values[0];
max = ui.values[1];
$('#range').text(min + ' - ' + max);
$.ajax({
url: '/dir_scan',
type: 'get',
data: {
min: min,
max: max
},
dataType: 'json',
success: function(response) {
var albums;
albums = response;
$.each(albums, function(index, obj) {
var albumname, artist, li_tag;
li_tag = '';
albumname = obj.AlbumName;
artist = obj.Artist;
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
}
});
}
});
});
As Will said in the comments, the JSON looks off.
But, you're on the right track of using .each, as it looks that you're returning an array of objects.
Here's an example of what to do:
var li_tag = '';
$.each(albums, function(index, obj) {
var albumname = obj.AlbumName;
var artist = obj.Artist
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
Additionally, 'albums' should be set to the returned response of the success function. You're potentially creating a bunch of headache to try and decipher from the window.location; especially since the json example looks malformed. And, any work done with the data returned from the ajax call, should occur in the success function.
Here is how iteration worked for this situation. Comments in code -
success: function(response) {
var albums;
// side issue - but I had to clear the div to get a complete refresh
$('#result').empty();
albums = response;
$.each(albums, function(key, value) {
var albumname, li_tag, path;
li_tag = '';
// I found I had to do this parseJSON call otherwise
// I had no correct key/value pair, even though I had set dataType
// to JSON
albumname = jQuery.parseJSON(key);
path = albumname[1];
li_tag += '<li ><a href=/album' + encodeURI(albumname[1]) + '>' + albumname[0] + '</a href></li>';
$('#result').append($(li_tag));
return console.log;
});
Actually, value in the code is just the index number, but I had the actual key/value pair separated by commas, so again the parseJSON seemed to be the only way it would work. This, despite trying things like split and substr. Hope my answer is clear if not I can edit.

How Show data from for a miltiple list return by JSON funtion?

My Models:
ClassAllocate: Id, DepartmentId, CourseId, RoomId, DayId, StartTime, EndTime
Course: Id, CourseCode, CourseName, DepartmentId
Room: Id, RoomNumber
Day: Id, DayName
I am trying to search courses by department ID from "ClassAllocates" table in view page and trying to display only those courses schedule/allocation details.
I am using JSON to send lists from controller to view. I need to send multiple lists of list from a JsonResult function. I can send them ( I tried to send 2 lists), but, I can't display them. it is showing [object Object] or nothing or undefined in my attempts.
I am including my Controller funtion and Javascript in view:
1st: Controller Function
public JsonResult GetCourseIdListByDepartmentId(int departmentId)
{
var x = db.ClassAllocates.DistinctBy(m => m.CourseId).Where(m => m.DepartmentId == departmentId).ToList();
var r = db.ClassAllocates.DistinctBy(m => m.RoomId).Where(m => m.DepartmentId == departmentId).ToList();
var all = new [] {x,r}.ToList();
return Json(all, JsonRequestBehavior.AllowGet);
}
2nd: View Java Script
<script>
$("#DepartmentId").change(function () {
var dptId = $("#DepartmentId").val();
//alert(dptId);
$(".RowClass").empty();
var json = {
departmentId: dptId
};
$.ajax({
type: "POST",
url: '#Url.Action("GetCourseIdListByDepartmentId", "ClassAllocates")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$(".table2").append(
'<tr class="RowClass">' +
'<td>' + value.Couse + '</td>'
+ '<tr>');
});
}
});
});
This result in:
undefined
I need, CourseCode, CourseName and RoomNumber
I got a way. As JSON returns List or list, then I need to write for loop twice after JSON success in View code or client side code.
$.each(data, function (key, value) {
if (key==0) {
$.each(this, function (k, v) {
$(".table2").append(
'<tr class="RowClass">' +
'<td>' + v.Course.CourseCode + '</td>'
+ '<tr>');
});
}
});
Now I am trying to pass and get more complex data.

how to store array of objects using localstorage fron one file to other file

I am new to localstorage.I am trying to store json data in one file and retrieving the data in other file.Below is my json data which i have fetched from an url.I have tried storing feeds data using using localstorage now i am tring to fetch the data in other html file.But i am getting only the final object from the feeds.How can i get all the feed objects in other file.
{
"channel":{
"id":9,
"name":"my_house",
"description":"Netduino Plus connected to sensors around the house",
"latitude":"40.44",
"longitude":"-79.9965",
"field1":"Light",
"field2":"Outside Temperature",
"created_at":"2010-12-14T01:20:06Z",
"updated_at":"2017-02-13T09:09:31Z",
"last_entry_id":11664376
},
"feeds":[{
"created_at":"2017-02-13T09:07:16Z",
"entry_id":11664367,
"field1":"196",
"field2":"31.507430997876856"
},{
"created_at":"2017-02-13T09:07:31Z",
"entry_id":11664368,
"field1":"192",
"field2":"30.743099787685775"
},{
"created_at":"2017-02-13T09:07:46Z",
"entry_id":11664369,
"field1":"208",
"field2":"28.280254777070063"
}]}
One.html:-(here i am storing all the feeds data)
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
other.html:(here i am trying to fetch the localstorage data)
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field2 = "+fd2);
}
</script>
Because you are over-riding the localStorage item in your for Loop.
The required for loop when simplified looks like:
json1.feeds.forEach(function(feed, i) {
localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
localStorage.setItem('Field1', feed.field1);});
That's why after the loop is completed. The Created_at field would only have the value of the most recently processed item in the array i.e. the last element. What you need to is create a corresponding array where each element would correspond to a feed item that you are reading from the API response.
Now, localStorage can simply store key value pairs. It doesn't have support for types like array. What you can do is something on these lines (Untested Code):
json1.feeds.forEach(function(feed, i) {
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
});
Yes, You will have to check if feedsArray key exists or not and set it as an empty array the first time. I have deliberately not put in the entire code as it is quite simple and should be good exercise for you.
So, once you are done and you want to read all the feeds from localStorage. Just get the feedsArray key and parse it and then iterate over it. Put simply, the basic idea is to have a JSON array of feeds and store it as a string with key feedsArray in localStorage.
The code snippet I have given above can get you started toward the solution I propose.
Relevant SO Post
The answer for the above issue is below.through which i got the solution.But not too sure if der is any wrong.
one.html:
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]')
}
});
other.html:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]');
//feedsArray.push(savedArr);
}
console.log(savedArr);
document.writeln("<br>FEEDS = "+savedArr);
}
</script

GiantBomb API Work

I have made an account and have my api key currently i just want a simple search box and button that when hit will list the game and the image of that game
Have linked the site info below
http://www.giantbomb.com/api/documentation
I want to run is and get the output using json and jquery any help welcome
This is a working search now some what does not allow the user to enter in a new value and there is a problem bring up the image
two main problems wont load the image just says undefined and cant figure out how to make it a full search only when he user enters a new title
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://api.giantbomb.com/search/",
type: "get",
data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
dataType: "jsonp"
});
});
function gamer(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
});
table += '</table>';
$('#myelement').html(table);
}
</script>
</head>
<body>
<h1>Game Search</h1>
<input id="game" type="text" /><button id="search">Search</button>
<div id="myelement"></div>
</body>
</html>
Your working code as per standard of the giantbomb docs:
var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";
// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";
$(document).ready(function() {
// send off the query
$.ajax({
url: GamesSearchUrl + '&query=' + encodeURI(query),
dataType: "json",
success: searchCallback
});
// callback for when we get back the results
function searchCallback(data) {
$('body').append('Found ' + data.total + ' results for ' + query);
var games = data.game;
$.each(games, function(index, game) {
$('body').append('<h1>' + game.name + '</h1>');
$('body').append('<p>' + game.description + '</p>');
$('body').append('<img src="' + game.posters.thumbnail + '" />');
});
}
});
http://jsfiddle.net/LGqD3/
GiantBomb Api example/explanation
First get your api key
Key: http://www.giantbomb.com/api/
Documentation: http://www.giantbomb.com/api/documentation
Your base url:
http://www.giantbomb.com/api/
Your url structure:
/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS
/RESOURCE/ID example: /game/3030-38206/
The type of resource you which to return, in your case a search. Sometimes.. in case of a specific game you also want to pass in the ID under /ID (like in the example)
api_key
Your api key
You need this otherwise you cannot use the api :)
format
The format you which to output, in this case json.
FILTERS example: /search?limit=100
This manipulates the resourses output
See under the resources in the documentation for a what you can do.
FIELDS example: /search?field_list=description,
Which field to return, use this to "reduce the size of the response payload"
A game request for it's name & description would be:
http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description
A search request
Lets say we want to search for the game "Elder scroll online".
You would construct your url like this:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game
To implement this in with $.ajax:
The ajax function
/*
* Send a get request to the Giant bomb api.
* #param string resource set the RESOURCE.
* #param object data specifiy any filters or fields.
* #param object callbacks specify any custom callbacks.
*/
function sendRequest(resource, data, callbacks) {
var baseURL = 'http://giantbomb.com/api';
var apiKey = '[YOUR-API-KEY]';
var format = 'json';
// make sure data is an empty object if its not defined.
data = data || {};
// Proccess the data, the ajax function escapes any characters like ,
// So we need to send the data with the "url:"
var str, tmpArray = [], filters;
$.each(data, function(key, value) {
str = key + '=' + value;
tmpArray.push(str);
});
// Create the filters if there were any, else it's an empty string.
filters = (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';
// Create the request url.
var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;
// Set custom callbacks if there are any, otherwise use the default onces.
// Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it.
// If not "||"" set an default function.
var callbacks = callbacks || {};
callbacks.beforeSend = callbacks.beforeSend || function(response) {};
callbacks.success = callbacks.success || function(response) {};
callbacks.error = callbacks.error || function(response) {};
callbacks.complete = callbacks.complete || function(response) {};
// the actual ajax request
$.ajax({
url: requestURL,
method: 'GET',
dataType: 'json',
// Callback methods,
beforeSend: function() {
callbacks.beforeSend()
},
success: function(response) {
callbacks.success(response);
},
error: function(response) {
callbacks.error(response);
},
complete: function() {
callbacks.complete();
}
});
}
search function
function search() {
// Get your text box input, something like:
// You might want to put a validate and sanitation function before sending this to the ajax function.
var searchString = $('.textox').val();
// Set the fields or filters
var data = {
query: searchString,
resources: 'game'
};
// Send the ajax request with to '/search' resource and with custom callbacks
sendRequest('/search', data, {
// Custom callbacks, define here what you want the search callbacks to do when fired.
beforeSend: function(data) {},
success: function(data) {},
error: function(data) {},
complete: function(data) {},
});
}
Example of a get game function
function getGame() {
// get game id from somewhere like a link.
var gameID = '3030-38206';
var resource = '/game/' + gameID;
// Set the fields or filters
var data = {
field_list: 'name,description'
};
// No custom callbacks defined here, just use the default onces.
sendRequest(resource, data);
}
EDIT: you could also make a mini api wrapper out of this, something like:
var apiWrapper = {};
apiWrapper.request = function(resource, data, callbacks) {
// The get function;
};
apiWrapper.search = function(data) {
// The search function
};
apiWrapper.getGame = function(id, data) {
// The game function
}
apiWrapper.init = function(config) {
var config = config || {};
this.apiKey = config.apiKey || false;
this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}
apiWrapper.init({
apiKey: '[API-KEY]'
});
Have not tested the code, so there might be a bug in it, will clean it up tommorow :)
Edit: fixed a bug in $.ajax

Skip duplicate items while rendering page from json

I'm rendering page using ajax and json. Structure of my json is {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]
How do i make ajax loading data only once one if 'points' duplicates in any of hashes?
E.g. i have json with few hashes in which 'points' have same value
Here is my code
$("#page").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/file.json",
dataType: "json",
error: function (data, tex
tStatus){
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var seen = {};
$.each(data.rewards, function(key, val){
lis += "<div class = 'reward-ui ui-block-" + String.fromCharCode(97 + key%3) + "'><a href ='#' class ='ui-link-inherit'>" + val.points + "</a></div>";
});
$(".ui-grid-b").html(lis);
});
//$('.even-odd').listview('refresh');
})
});
Add a local array which will store all the items used. Push into this array in $.each function and before doing lis += " " check if the value already exists in the temp array.
Other than that you could try server side sorting before retrieving data ... like suggested above.

Categories