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>
Related
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}
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) {
},
})
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');
}
});
Jquery autocomplete for textbox search is not working ,webservice is called but the value is not binded to the textbox .please let me know what's wrong in this code.
.aspx page:
<asp:TextBox ID="tbStudentName" runat="server" class="tbStudentName" />
<asp:Button ID="btnStudentSearch" runat="server" meta:resourcekey="btnSearch" OnClick="btnStudentSearch_Clicked" />
Script:
function AutoCompleteName(target) {
var xhr;
$j("." + target.className).autocomplete({
source: function (request, response) {
if (xhr && xhr.readystate != 4) {
xhr.abort();
}
xhr = $j.ajax({
url: "../ServiceInterface/StudentLookupService.asmx/StudentSearch",
data: "{'pStudentId': '', 'pStudentName': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($j.map(data.d, function (item) {
return {
label: item.StudentId + ' : ' + item.LastName + ', ' + item.FirstName + ' ' + item.MiddleName,
value: item.FirstName + ' ' + item.LastName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
response([]);
}
});
},
select: function (event, ui)
{
$j("." + target.className).val = ui.item.firstName + ' ' + ui.item.lastName;
return true;
},
minLength: 1
});
}
Also when i enter two character in search box am getting error function,for 3 or more characters only the web service is called.
Please let me know your suggestions to make it work
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.