select2 ajax not working - javascript

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.

Related

Why is the data from the database not displayed in the select through ajax?

Good evening, I'm sorry, this text was translated through google translator
I'm not very good at parsing javascript, when I copy this code from the documentation, the data is successfully loaded and displayed
$("#select-repo").selectize({
valueField: "url",
labelField: "name",
searchField: "name",
create: false,
render: {
option: function (item, escape) {
return (
"<div>" +
'<span class="title">' +
'<span class="name"><i class="icon ' +
(item.fork ? "fork" : "source") +
'"></i>' +
escape(item.name) +
"</span>" +
'<span class="by">' +
escape(item.username) +
"</span>" +
"</span>" +
'<span class="description">' +
escape(item.description) +
"</span>" +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + "</li>" : "") +
'<li class="watchers"><span>' +
escape(item.watchers) +
"</span> watchers</li>" +
'<li class="forks"><span>' +
escape(item.forks) +
"</span> forks</li>" +
'<li class="stars"><span>' +
escape(item.followers) +
"</span> stars</li>" +
"</ul>" +
"</div>"
);
},
},
score: function (search) {
var score = this.getScoreFunction(search);
return function (item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "https://api.github.com/legacy/repos/search/" + encodeURIComponent(query),
type: "GET",
error: function () {
callback();
},
success: function (res) {
callback(res.repositories.slice(0, 10));
},
});
},
});
But as soon as I change the data to my own, my code stops working
$(".add-items-select").selectize({
valueField: "id",
labelField: "name",
// searchField: "name",
create: true,
render: {
option: function (item, escape) {
return "<div>" + '<span class="title">' + escape(item.id) + "</span>" + "</div>";
},
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "http://127.0.0.1:8000/warehouse/api/products/" + encodeURIComponent(query)+ "/?format=json",
type: "GET",
error: function () {
callback();
},
success: function (res) {
callback(res);
callback(console.log(res));
},
});
},
});
Data is displayed in the console, but the render function does not work
Here is my json
{"id":1,"company_detail":{"id":1,"name":"test","adress":null},"articul":"1","name":"teyit","category_detail":null,"stock":0,"sell_price":"123.00","last_buy_price":"1.00","archived":false}

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>

Set the initial value for select by selectize.js?

I want to display the initial value when initialized but it doesn't seem to work. I tried to research and found a way but couldn't.
HTML
<select class="select-links" multiple id="selectID">
<option value="KR" selected="selected">Koren</option>
</select>
JS
var select = $('.select-links').selectize({
valueField: 'url',
searchField: 'title',
plugins: ['remove_button'],
options: [],
render: {
option: function (data, escape) {
return '<div class="option">' +
'<span class="title">' + escape(data.title) + '</span>' +
'<span class="url">' + escape(data.url) + '</span>' +
'</div>';
},
item: function (data, escape) {
return '<div class="item">' + escape(data.title) + '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "/account.json",
type: 'POST',
error: function () {
callback();
},
success: function (data) {
var Array_User = [];
for (var i = 0; i < data.array.length; i++) {
var obj = data.array[i];
Array_User.push({ id: obj.ID, name: obj.Full_Name, email: obj.Email });
}
callback(Array_User)
}
});
}
});

Json not work in asp.net mvc

I wanna to use this json to my sites shopping cart .it works well in visual studio 2017 but in visual studio 2013 it does not work. please help me to solve it.
function AddtoCart() {
$.ajax({
url: '/Home/AddToCart',
type: 'POST',
dataType: 'Json',
data: {
ProductID: #Model.product.id,
count: My_Count.value
},
error: function(err) {
alert(err.status);
}
}).done(function(data) {
$('#Total_Cost').text(data.Total_Price)
var Text = "";
$.each(data.lst_ShoppingCart, function(index, val) {
Text += "<tr><td class='col-sm-8 col-md-6' ><span id='Product_Name'>" + val.Product_Name + "</span></td ><td class='col-sm-1 col-md-1' style='text-align: center'><input type='text' class='form-control' id='exampleInputEmail1' value='" + val.Count + "'></td><td class='col-sm-1 col-md-1 text-center'><span id='Product_Cost'>" + val.Single_Price + "</span></td><td class='col-sm-1 col-md-1 text-center'><span id='Total_ProCost'>" + val.Price + "</span></td><td class='col-sm-1 col-md-1'><button type='button' onclick='RemoveCart(" + val.ID + ")' class='btn btn-danger'>Remove</button></td></tr>";
})
$('#Pro_Cart').html(Text);
});
}
also I know that this part of code not working:
url: '/Home/AddToCart',
type: 'POST',
dataType: 'Json',
data: {
ProductID: #Model.product.id,
count: My_Count.value
},

Pagination in popup from JSON data

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

Categories