Skip duplicate items while rendering page from json - javascript

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.

Related

Read encoded data in ajax request

My ajax retrieves the following response in the console:
PHP
$checkout_session_data = json_encode(['id' => $checkout_session->id]);
wp_send_json_success( $checkout_session_data );
// this is then retuend to the JS ajax function.
data: "{\"id\":\"cs_test_a1SOgBGIPsRrECu5pP8TDCW16JYMMHnGnmfh7Lp6qf8bvwTk3hK97sI7e7\"}"
success: true
I'm unclear how to get the ID value from the response from within the .done part of my ajax function.
.done( function(response) {
if( response.success == true ) {
console.log(response);
}
Attempts:
console.log(response.data.id);
console.log(response[0].id);
Your data is double encoded, wp_send_json_success encodes the data passed to it to JSON so do not json_encode your data before you pass it to wp_send_json_success,
$checkout_session_data = ['id' => $checkout_session->id];
wp_send_json_success( $checkout_session_data );
.done( function(response) {
if( response.success == true ) {
console.log(response.data.id);
}
}
Instead of using the ajax request, you would be better served by using the getJSON function here. A sample of the code is shown below.
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
});
You can find further details from this link https://api.jquery.com/jquery.getJSON/

Why am i receiving error 404 when fetching video data?

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);
})

Jquery get data from JSON (undefined)

When i try to get value from json data i getting undefined
$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
alert(data); // return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
alert(data.start); // return undefined (should be here 2015-03-04)
});
I need get only start value from data, how can i fix this?
If your data is not an object, you need to make an object out of it to be able to access its values. I am not sure what it is at the moment. Hence, I've put a condition to check the type and then alert accordingly.
$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
alert(data);
// return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
if (typeof data === "object") {
alert (data[0].start);
} else {
alert (JSON.parse(data)[0].start);
}
});
A demo#fiddle along the same lines.
Use this :
$.get( url, function( data ) {
/* do stuff */
}, 'json');
or this :
$.getJSON( url, function( data ) {
/* do stuff */
});
Before Accessing a Json data from 'data' object, you need to parse it to Json Object.
you can achieve this as below:
var parsedJson=$.parseJSON(data)
Here after you can access the json objects like:
alert(parsedJson[i].start);
where 'i' is the index on N-th data set in the Json object, it can take any numeric value ranging from 0,1,..N
Hope this Helps!!
you can do like following:
$.ajax({
type: 'GET',
url: baseURL + 'vacation/show/' + name_surname,
dataType: 'json',
success: function(data) {
for(var i = 0; i < data.length; i++) {
console.log(data[i].start);
}
},
error: function(e) {
console.log(error);
}
});
Ty to all, it works fine now, just wondering, or i doing good in my next step, if i retrieve from array for loop and then push only dates into array again to get min date, or it will not be a duplication of work?
$.getJSON( baseURL + 'vacation/show/' + name_surname, function( data ) {
if(data != '') {
var dates = [];
for(var i = 0; i < data.length; i++) {
var date = new Date(data[i].start);
dates.push(date);
}
var minDate = new Date(Math.min.apply(null, dates));
var year = minDate.getFullYear();
var month = minDate.getMonth();
$('#calendar').fullCalendar('gotoDate', year, month);
}
});

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

Store items in array with using them later

I have code, which get json file from server and then render some if its elements on the page. In this code i also skip items with duplicate value of key "points". My question is, how do i make these skipped items to store somewhere, so if i click on item that has duplicate, it would link me to some other page with list of these duplicates?
Here is my code
var request = $.ajax({
type: "GET",
url: "example.com/rewards.json"
dataType: "json",
error: function (data, textStatus){
console.log( "it`s error" );
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 arr = [];
var iter = 0;
$.each(data.rewards, function(key, val){
if ($.inArray(val.points, arr) == -1)
{
lis += "<div class = 'ui-block-" + String.fromCharCode(97 + iter%3) + "'><a href ='#' class ='ui-link-inherit'>" + val.points + "</a></div>";
arr.push(val.points);
iter += 1;
}
});
$("#rewards_table").html(lis);
})
Description of what i want might be a little confusable, so feel free to ask me anything
You just do exactly that: Store them somewhere for use later.
For example, put this line at the top of your code:
var duplicates = [];
...and add this else to the if inside your $.each iterator function:
else
{
duplicates.push(val.points);
}
(I think I got your bracing style right there, a bit alien to me. :-) )
The above assumes all of your code is held in some kind of containing function, to avoid creating globals, and so duplicates (like your existing request variable) won't end up becoming a global.

Categories