Pagination in popup from JSON data - javascript

I am looking to add pagination in a pop-up window. I tried looking for a plug in but didn't find anything that would work with a pop-up.I am getting JSON data. the reason is because of the data coming back been too big to even allow the pop-up window to scroll. Has anyone done something like that where I can see how its done. Sample code below.
Thank you!
JSON Data Sample:
[
{
"name" : "Jonathan Suh",
"gender" : "male"
},
{
"name" : "William Philbin",
"gender" : "male"
},
{
"name" : "Allison McKinnery",
"gender" : "female"
},
{
"name" : "Becky Borgster",
"gender" : "female"
},
{
"name" : "Victoria Einsteen",
"gender" : "female"
}
{
"name" : "Suh EH",
"gender" : "male"
},
{
"name" : "Mar Lee",
"gender" : "female"
},
{
"name" : "Croc Dyllo",
"gender" : "male"
},
{
"name" : "Auter Naddo",
"gender" : "male"
},
]
JS code:
$("document").ready(function(){
$('#myForm').submit(function(e) {
// To stop the default behavior, a # will be added to the URL in the address bar.
e.preventDefault();
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
dataType: "json",
url: "get_json.pl",
data: datastring,
success: function(data) {
var stable = '<div class="popup-inner">' +
' <h2>Results</h2>' +
' <div>';
$.each(data,function(key,value) {
stable += '<p>Name: ' + value.name + ' | ' + 'Gender: ' + value.gender + '</p>';
});
stable += ' </div>'+
'<p><a data-popup-close="popup" href="#">Close</a></p>'+
'<a class="popup-close" data-popup-close="popup" href="#">x</a>'+
'</div>';
// Popup will be called here and opended in the div below
$('#popup').append(stable).fadeIn(350);
// This function will close the popup on click.
$('[data-popup-close]').on('click', function(e) {
var targeted_popup_class = jQuery(this).attr('data-popup-close');
$('#'+targeted_popup_class).fadeOut(350);
// Or use the id from the div below to close it.
//$('#popup').fadeOut(350);
e.preventDefault();
});
},
error: function() {
alert('Error handing data');
}
});
});
});
HTML code:
<form id="myForm">
<input type="text" name="name" value="" placeholder="Search by Name" />
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="popup" id="popup">
</div>
Thanks again!

Here you have an easy option to do it. You can complicate it as much as you want....
$.ajax({
type: 'POST',
dataType: 'json',
url: 'get_json.pl',
data: datastring,
success: function(data) {
var stable = '<div class="popup-inner">' +
'<h2>Results</h2>' +
'<div id="results">';
$.each(data,function(key,value) {
stable += '<p>Name: ' + value.name + ' | ' + 'Gender: ' + value.gender + '</p>';
});
stable += '<div id="pagination">' +
'<span id="previous">Previous</span> ' +
'<span id="next">Next</span>' +
'</div>' +
'</div>' +
'<p><a data-popup-close="popup" href="#">Close</a></p>' +
'<a class="popup-close" data-popup-close="popup" href="#">x</a>' +
'</div>';
// Popup will be called here and opened in the div below
$('#popup').append(stable).fadeIn(350);
// Pagination.
var pageSize = 4,
pageStart = 0,
nItems = $('div#results p').length;
$('div#results p').hide().slice(pageStart,pageStart+pageSize).show();
$('div#pagination span').click(function() {
if ( (this.id == 'previous') && (pageStart>=pageSize) )
pageStart -= pageSize;
else if ( (this.id == 'next') && ((pageStart+pageSize)<nItems) )
pageStart += pageSize;
$('div#results p').hide().slice(pageStart,pageStart+pageSize).show();
});
// This function will close the popup on click.
$('[data-popup-close]').on('click',function(e) {
e.preventDefault();
$('div#popup div.popup-inner').fadeOut(350);
});
},
error: function() {
alert('Error handing data');
}
});

Related

jQuery - Getting Correct UserID - AJAX

so I am at a bit of a bind here. So I have 2 jQuery scripts that handle a simple database row update (per the user ID, session), this lets the user send a "Gift" that adds value to the users database row column "bonus".
I got this working practically perfect, but the problem is: It will only get the first ID of the results when gifting, not any other user ID. I suspect this is a fault in the looping logic.
RequestBin tells me I have my correct ID for myself, and the user ID is stuck with the first iterated userid (we cant send to any other user ID). We need to be able to gift any result (user ID).
We use a dialog to trigger the AJAX call with Yes / No. Yes firing the AJAX event, no closing model.
The AJAX JS - Sends value to database
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function () {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
var sender = $('input[name=sender]').val();
var receiver = $('input[name=receiver]').val();
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function () {
$('#gift-bonus-status').text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function (response) {
$('#gift-bonus-status').text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function () {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
function fetchTopTransfers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_user_list.php',
method: 'GET',
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
$('input[name=receiver]').val(item.user_id);
html_to_append +=
'<div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
formatBytesProduct(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\')" id="gift-bonus-status">Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div></div><div style="clear:both"></div><input type="hidden" name="sender" value="<?=$account->getId()?>" /><input type="hidden" name="receiver" value="' +
item.user_id + '" />';
});
$("#top-transfers").html(html_to_append);
}
});
}
fetchTopTransfers();
setInterval(function () {
fetchTopTransfers()
}, 5000);
AJAX responce:
What is happening here???
Any help is much appreciated
As there many inputs with name receiver that's why you are not able to pass correct values. So, inside your ConfirmDialog function pass this as well it will refer to current element which is clicked. Then , inside your function to get required values you can use $(this).closest(".outer").find(..)...
Demo Code :
//just for demo..
var data = [{
"user_id": 1,
"product_id": 12,
"username": "acc",
"name": "swi",
"progress": "20",
"speed": 15
}, {
"user_id": 2,
"product_id": 12,
"username": "acc",
"name": "swi22",
"progress": "10",
"speed": 12
}]
var html_to_append = "";
$.each(data, function(i, item) {
//give outer div.. also pass `this` inside your function
html_to_append +=
'<div class="outer"><div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\',this)" >Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div><div style="clear:both"></div><input type="hidden" name="sender" value="23" /><input type="text" name="receiver" value="' +
item.user_id + '" /></div>';
});
$("#top-transfers").html(html_to_append);
//add el it refer to `this`
function ConfirmDialog(message, el) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function() {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
//get closest div(outer) then find required inputs values
var sender = $(el).closest(".outer").find('input[name=sender]').val();
var receiver = $(el).closest(".outer").find('input[name=receiver]').val();
console.log("Reciver --" + receiver + " Sender ---" + sender)
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function() {
//use el here as well..
$(el).text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function(response) {
//use el here as well
$(el).text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function() {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<div id="top-transfers">
</div>

Jquery repeater with select2 not working properly

I am seaching from 2 days about this issue.
The first element is working perfectly. But after repeat the element, previous element's select2 fields destroyed automatically.
There is two rop divs in repeater. When first one selected by the ajax request I am appending the options to values section.
Here is the screenshot for reference.
Here is the code for repeater and select2 initialization.
<script>
$(function () {
$(".attribute_list").on('change', ".attribute", function (e) {
var attr_name = $(this).attr('name');
var attr_id = $(this).val();
$.ajax({
type: "POST",
url: "{{ route('products.getValue') }}",
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
contentType: "application/json",
dataType: "json",
data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
success: function (data) {
var attribute_value = data.attribute_value;
var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';
if (attribute_value) {
$(field_name).empty();
$.each(attribute_value, function (key, value) {
$(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
});
// $(field_name).select2();
} else {
$(field_name).empty();
}
}
});
});
});
</script>
<script>
// $("#attribute_button").click(function(){
// $('#attribute_values').select2({
// placeholder: "select attribute value"
// });
// });
window.onload = function () {
$('.attribute_values').select2({
placeholder: "select attribute value",
allowClear: true
});
}
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
$('.attribute_values').select2({
placeholder: "select attribute value"
});
},
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
ready: function (setIndexes) {
},
})

How to set response data to javascript code

How to set response data
$.ajax({
type : "POST",
async: true,
url : "<?php echo base_url(); ?>" + "Graphs/get_graphs",
dataType: 'json',
data :{hotel_name_realm:$("#hotel_names").val()},
success : function(res){
obj = JSON.parse(res);
console.log(obj.upload);
console.log(obj.download);
series: [{
name: 'Download',
data: [
(obj.Download) // I need set obj.download data here
]
}
}
Here is my console.log(obj) image
i do like this,
$.ajax({
method: "POST",
url: "chat/searchuser",
data: {name: $(this).val(), length: "10"}
})
.done(function (data) {
$('#scroll_user').val('10');
var html = '';
$.each(JSON.parse(data).data, function (k, v) {
html += '<div class="row sideBar-body getUserdata userchat" data-username="' + v.fname + '" data-id="<?php echo $key; ?>" onclick="showDiv()" id="' + v.fname + '"><div class="col-sm-3 col-xs-3 sideBar-avatar"><div class="avatar-icon"><img src="<?= base_url('assets/user2.jpg') ?>"></div></div><div class="col-sm-9 col-xs-9 sideBar-main"><div class="row"><div class="col-sm-12 col-xs-12 sideBar-name" data-username="' + v.fname + '"><span class="name-meta">' + v.fname + ' ' + v.lname + '(' + v.username + ')</span></div></div></div></div>'
$('#usersindiv').html(html);
});
}).fail(function () {
alert("failed");
});
You are doing it right, you just missed the right square bracket. JS is also case sensitive, obj.Download is not obj.download
$.ajax({
type : "POST",
async: true,
url : "<?php echo base_url(); ?>" + "Graphs/get_graphs",
dataType: 'json',
data :{hotel_name_realm:$("#hotel_names").val()},
success : function(res){
obj = JSON.parse(res);
console.log(obj.upload);
console.log(obj.download);
series: [{
name: 'Download',
data: [
(obj.Download) // shouldn' it be obj.download? (small D)
]
] // you are missing the right bracket here
}
}

search box result == Json result

I have a Node.js server that reads a JSON file and there are a lot of information in it. One of them is ID of a person, I have a search box in my HTML page I wanna right a jquery method(ajax required) for the client side to find if the ID that the user put in the search box is the same as the ID in JSON, if it is I wanna return some information about that person, let's say name and username of the user.
Note: I am 100% sure that my server.js file works.
Please help me, I am kind of a newbie in Jquery.
I have so far;
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
url: '/url_of_the_related_server_side',
dataType: 'json'
})
.done(function(data){
console.log(data);
alert(JSON.stringify(data));
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.search_box_ID == any_function_variable_name.name_in_the_JSON_file_for_one_of_the_searched_ID){
$userElement = $("<li>").html("<strong>ID: </strong>" + any_function_variable_name.id); //id is defined in JSON and I was able to use in another part of the jquery
$userBlock = $("<ul>")
.append(
$("<li>").html("<strong>Name: </strong>" + any_function_variable_name.name) //name of the user
)
.append(
$userElement
)
.append(
$("<li>").html("<strong>User User Name: </strong>" + any_function_variable_name.userName)
);
$any_function_variable_nameBlock.insertAfter("#search");
}
});
});})})
Note: I don't know if I could close the brackets right.
Thanks in advance!
I guess you are looking for something like as shown below ...
Instead of making an ajax call, I wrote with static data as below ...
HTML
<input id="searchBox" type="text" />
<button id="id_of_the_search_box_button">
Search
</button>
<ul>
</ul>
JS
var data = [
{
"id": 37595960858,
"in_reply_to_screen_name": null,
"user": {
"id": 2384451,
"id_str": "238678",
"name": "Doga I",
"screen_name": "IDoga"
}
},
{
"id": 65739068412,
"in_reply_to_screen_name": null,
"user": {
"id": 2878009,
"id_str": "235678",
"name": "Jon Doe",
"user_name": "JD"
}
}
];
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
var searchText = parseInt($('#searchBox').val());
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.id === searchText){
$("ul")
.append('<li> <strong>ID: </strong>' + any_function_variable_name.user.id)
.append('<li> <strong>User Name: </strong>' + any_function_variable_name.user.user_name)
.append('<li> <strong>Name: </strong>' + any_function_variable_name.user.name)
.append('<li> <strong>Screen Name: </strong>' + any_function_variable_name.user.screen_name);
} //End if
}); //End forEach
});
});
which makes your ajax call like this ...
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
url: '/url_of_the_related_server_side',
dataType: 'json'
})
.done(function(data){
var searchText = parseInt($('#searchBox').val());
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.id === searchText){
$("ul")
.append('<li> <strong>ID: </strong>' + any_function_variable_name.user.id)
.append('<li> <strong>User Name: </strong>' + any_function_variable_name.user.user_name)
.append('<li> <strong>Name: </strong>' + any_function_variable_name.user.name)
.append('<li> <strong>Screen Name: </strong>' + any_function_variable_name.user.screen_name);
} //End if
}); //End forEach
});
});
});
Following is the fiddler
https://jsfiddle.net/rrtbz4bo/7/
Enter 37595960858 in search box and hit search.
UPDATE: call the /find/id?id=... api directly if it returns data like
{
"id": 37595960858,
"in_reply_to_screen_name": null,
"user": {
"id": 2384451,
"id_str": "238678",
"name": "Doga I",
"screen_name": "IDoga"
}
}
Then following should work.
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
//Or whatever your URL structure is
url: 'http://127.0.0.1:5230/find/id?Id=' + $('#searchBox').val(),
dataType: 'json'
})
.done(function(data){
$("ul")
.append('<li> <strong>ID: </strong>' + data.user.id)
.append('<li> <strong>User Name: </strong>' + data.user.user_name)
.append('<li> <strong>Name: </strong>' + data.user.name)
.append('<li> <strong>Screen Name: </strong>' + data.user.screen_name);
});
});
});
If this doesn't work, post a fiddler and i'll try and make it work.
Hope this helps ...

select2 ajax not working

I'm working with select2 library to make a dropdown using ajax. I cant make it work. Here is my code:
$("#guests").select2({
multiple: true,
minimumInputLength: 1,
formatInputTooShort: function () {
return "Enter 1 Character";
},
data: function() {
return data;
},
ajax: {
url: 'some url',
dataType: 'json',
processResults: function (data) {
// 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
return {
results: data.data,
pagination: {
more: 30
}
}
}
/*,
cache: true*/
},
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
})
function formatRepo (results) {
var markup = "<div class='select2-result-resultssitory clearfix'>" +
"<div class='select2-result-resultssitory__avatar'><img src='" + results.id + "' /></div>" +
"<div class='select2-result-resultssitory__meta'>" +
"<div class='select2-result-resultssitory__title'>" + results.text + "</div>";
if (results.description) {
markup += "<div class='select2-result-resultssitory__description'>" + results.guest_first_name + "</div>";
}
markup += "<div class='select2-result-resultssitory__statistics'>" +
"<div class='select2-result-resultssitory__forks'><i class='fa fa-flash'></i> " + results.guest_last_name + " Forks</div>" +
"<div class='select2-result-resultssitory__stargazers'><i class='fa fa-star'></i> " + results.guest_do_b + " Stars</div>" +
"<div class='select2-result-resultssitory__watchers'><i class='fa fa-eye'></i> " + results.text + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatRepoSelection(results) {
return results.text || results.guest_first_name;
}
html:
<select id="guests" class="form-control input-guests " data-placeholder="Search guest..." multiple=""></select>
here is the JOSN data i'm getting from remote url:
[{
"id": 1,
"guest_first_name": "Jon",
"guest_last_name": "Doe",
"guest_do_b": "1954-07-13T00:00:00+0100",
"text": "Jon Doe"
}, {
"id": 2,
"guest_first_name": "Janne",
"guest_last_name": "Doe",
"guest_do_b": "1960-01-14T00:00:00+0100",
"text": "Janne Doe"
}]
A bit late, but was your error that options.results is undefined?
If that's the case, then you may want to rename the function processResults to results
I know it's in the docs with the processResults function, but I had the same problem and this article had the solution for me.

Categories