I want to create paginate system. I have this code:
(function (name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: '/ajax/allads',
locator: 'items',
totalNumber: 3,
pageSize: 2,
ajax: {
beforeSend: function () {
container.prev().html('Loading...');
}
},
callback: function (response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '<ul>';
$.each(response, function (index, item) {
dataHtml += '<li>' + item.title+ '</li>';
});
dataHtml += '</ul>';
container.prev().html(dataHtml);
}
})
})('demo2');
It display 2 page but everytime it displayall result. Why?
This has to do with your backend system. The result is basically from your response. Or you have to make your question more clear.
Related
I have a jquery function that has an ajax call. I can't get the total price to come up even though it should be working. The class .cart-price is within .cart-body so I don't think its an issue with the template.
function refreshCart(){
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
//cartBody.html("<h1>Changed</h1>")
var productRows = cartBody.find(".cart-product")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data){
console.log("success")
console.log(data)
if (data.products.length > 1){
productRows.html(" ")
$(cartBody).empty()
$.each(data.products, function(index, value){
console.log(value)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
// console.log(data.total)
cartBody.find(".cart-total").text(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
$(cartBody).empty() was clearing everything in the table body. The solution was to create a new HTML table row outside of the table body.
I'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autocomplete widget to help user select one option. I know I'm terribly off the track.
My json file:
[
{"iata":"AAC", "name":"El Arish"},
{"iata":"AAE", "name":"Annabah"},
{"iata":"AAF", "name":"Apalachicola"},
{"iata":"AAG", "name":"Arapoti"},
{"iata":"AAH", "name":"Aachen"},
{"iata":"AAI", "name":"Arraias"},
{"iata":"AAJ", "name":"Awaradam"},
{"iata":"AAK", "name":"Buariki"},
{"iata":"AAL", "name":"Aalborg"},
{"iata":"AAM", "name":"Malamala"},
{"iata":"AAN", "name":"Al Ain"}
]
My JavaScript:
$(document).ready(function () {
$('#search').autocomplete({
source: function (request, response) {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON("beta.json", function (data) {
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.iata.search(myExp) !== -1) ||
(val.name.search(myExp) !== -1)) {
output += '<li>';
output += '<h2>' + val.iata + '</h2>';
output += '<p>' + val.name + '</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
)
});
}
});
});
I fixed some syntax errors and then wrote up this example to really get you jump started.
$( function() {
$.getJSON("http://neil.computer/stack/beta.json", function(data) {
autoComplete = [];
for (var i = 0, len = data.length; i < len; i++) {
autoComplete.push(data[i].name + ", " + data[i].iata);
}
$( "#tags" ).autocomplete({
source: autoComplete
});
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
You can push html to an array at request, pass array to response, at .autocomplete("instance")._renderItem create an <li> element with html set to second argument item, .value property, which should be html set within request and passed to response; append <li> to first argument ul, return ul from ._renderItem
var elem = $("#search");
$.ajaxSetup({
context: elem
});
elem.autocomplete({
minLength: 1,
source: function(request, response) {
$.getJSON("beta.json")
.then(function success(data) {
var searchField = elem.val();
var myExp = new RegExp(searchField, "i");
var res = [];
$.each(data, function(key, val) {
if ((val.iata.search(myExp) !== -1) ||
(val.name.search(myExp) !== -1)) {
res.push("<h2>" + val.iata + "</h2>" + "<p>" + val.name + "</p>")
}
});
response(res);
}, function error(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown) // log `$.ajax` errors
})
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>", {
html: item.value
}).appendTo(ul)
};
jsfiddle http://jsfiddle.net/wr1wg5df/11/
I'm trying to build a string depending on an image whether it exists or not, if it exists then build an image tag if it doesn't then create an empty div tag with a class .no-image how can I accomplish this - could some give me some help
$('#search_movies').select2({
ajax: {
url: "http://localhost:8000/admin/tmdb/search",
dataType: 'json',
delay: 250,
type: 'POST',
results: function (data, page) {
console.log(data);
return { results: data.d };
},
data: function (params) {
return {
q: params.term, // search term
// page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
//params.page = params.page || 1;
console.log(data)
return {
results: data.items,
// pagination: {
// more: (params.page * 30) < data.total_count
// }
};
},
cache: false
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
function formatRepo(repo) {
if (repo.loading) return repo.text;
var markup = '<div data-id="' + repo.id + '" class="option clearfix">';
markup += '<div class="option-image"><img alt="" src="' + repo.image + '"></div>';
markup += '<div class="option-content">';
markup += '<h4>' + repo.title + '</h4>';
markup += '<h4>' + repo.release_date + '</h4>';
markup += '<h4>' + repo.popularity + '</h4>';
markup += '</div>';
markup += '</div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.title || repo.text;
}
Instead of making formatRepo return the markup, make it pass the markup to a callback function like.
function formatRepo(repo, markupCallback) {
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
imageExists(repo.image, function(exists) {
var markup = '';
if(exists) {
markup += '<img src="' + repo.image + '">';
} else {
markup += '<div class="no-image"></div>';
}
// pass markup to markupCallback
markupCallback(markup);
});
}
// and then use it like
formatRepo(myRepo, function(markup){
// use markup here
});
I'm trying to create a youtube social feed that includes the video, title, description, date, and view count. I've got everything to work except for the last one, view count. I've been able to get the view counts to show up but they are always out of order and I'm lost on how to make them match up to their respective videos. I used this video as an initial tutorial: [https://www.youtube.com/watch?v=jdqsiFw74Jk][1] It got me this far, but now I'm lost again. Here is my code via code pen: [http://codepen.io/ThatsMyJams/pen/EjZWex][2]
here is my html:
<div id="container">
<h2>Results:</h2>
<ul id="results"></ul>
</div>
and here is my javascript:
var yourApiKey = 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE';
var channelName = 'GoogleDevelopers';
var vidCount = 5;
var vidHeight = 275;
var vidWidth = 400;
$(document).ready(function(){
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: yourApiKey},
function(data){
$.each(data.items, function(i, item){
console.log(item);
playerID = item.contentDetails.relatedPlaylists.uploads;
getVids(playerID);
})
}
);
function getVids() {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidCount,
playlistId: playerID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'},
function(data){
var output;
$.each(data.items, function(i, item){
console.log(item);
vidTitle = item.snippet.title;
videoID = item.snippet.resourceId.videoId;
vidDate = item.snippet.publishedAt;
vidDesc = item.snippet.description;
output = '<li>'+vidTitle+'<span class="date">'+vidDate+'</span><p class="description">'+vidDesc+'</p><iframe height="'+vidHeight+'" width ="'+vidWidth+'" src=\"//www.youtube.com/embed/'+videoID+'\"></iframe></li>';
//append to results list
$('#results').append(output);
getViews(videoID[i]);
})
}
);
}
function getViews() {
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
id: videoID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'},
function(data){
var output2;
$.each(data.items, function(i, item){
vidViews = item.statistics.viewCount;
output2 = '<span class="views">'+vidViews+'</span>'
//append to results list
$('#results li').each(function() {
$(this).append(output2);
});
})
}
);
}
});
I just want to get the viewCount for each video and insert it into the html much like I did for the title, date, etc. Any help would be greatly appreciated :)
Here's your modified code. this will display views at the end of each video:
var yourApiKey = 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE';
var channelName = 'GoogleDevelopers';
var vidCount = 5;
var vidHeight = 275;
var vidWidth = 400;
$(document).ready(function () {
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: yourApiKey
},
function (data) {
$.each(data.items, function (i, item) {
console.log(item);
playerID = item.contentDetails.relatedPlaylists.uploads;
getVids(playerID);
})
}
);
function getVids() {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidCount,
playlistId: playerID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'
},
function (data) {
var output;
$.each(data.items, function (i, item) {
console.log(item);
vidTitle = item.snippet.title;
videoID = item.snippet.resourceId.videoId;
vidDate = item.snippet.publishedAt;
vidDesc = item.snippet.description;
var viewCountId = "viewCount" + i;
output = '<li>' + vidTitle + '<span class="date">' + vidDate + '</span><p class="description">' + vidDesc + '</p><iframe height="' + vidHeight + '" width ="' + vidWidth
+ '" src=\"//www.youtube.com/embed/' + videoID + '\"></iframe>"<span id="' + viewCountId + '"></span></li>';
//append to results list
$('#results').append(output);
getViews(viewCountId);
})
}
);
}
function getViews(viewCountId) {
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
id: videoID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'
},
function (data) {
var output2;
$.each(data.items, function (i, item) {
$('#'+viewCountId).text("views=" + item.statistics.viewCount);
})
}
);
}
});
I need to use a switch statement to build the markups based on the retrieved feed. Although I'm able to retrieve the data, I wonder if it's correct to use two $(data.value.items).each(function (index, item) { to append the feed's titles to a select box as well as an unorder list. Any better way of doing the same thing?
$.ajax({
url: "http://www.zzz.com/text.json",
dataType: 'json',
success: function (data) {
item_html = parseData(feedformat, data)
var nextarea = $this.next('.area');
nextarea.append(item_html).slideDown();
},
error: function () {
area.html('fail'); }
});
function parseData(type, data) {
var item_html ='';
switch(type) {
case 'thisfeed':
item_html +='<select>';
$(data.value.items).each(function (index, item) {
item_html += '<option>'+item.title+'</option>';
});
item_html += '</select>';
item_html += '<ul>';
$(data.value.items).each(function (index, item) {
item_html += '<li>'+item.title+'</li>
});
item_html += '</ul>';
break;
}
return item_html;
}
You could just do both in the same loop, something like this
$.ajax({
url : 'http://www.zzz.com/text.json',
dataType : 'json',
success : function (data) {
var item_html = parseData(feedformat, data)
var nextarea = $this.next('.area');
nextarea.append(item_html).slideDown();
},
error: function () {
area.html('fail');
}
});
function parseData(type, data) {
switch(type) {
case 'thisfeed':
var select = $('<select />'),
ul = $('<ul />');
$(data.value.items).each(function (index, item) {
var option = $('<option />', {text : item.title}),
li = $('<li />', {text : '.......'});
select.append(option);
ul.append(li);
});
}
}
return select.add(ul);
}