WordPress with select2 and Toastr get previous selected value destroys select2 behavior - wordpress

I am using WordPress and I have used Select2 and Toastr libraries successfully.
Basically I have a dropdown and if I change, Toastr will ask whether I need to update or not.
If I click on "Yes" then it will update and if I click on "No" then my dropdown should set previous value and nothing will happen.
Currently its selecting previous value but then if I open the same dropdown try to click on it to search then its saying "The results could not be loaded".
Here is my JS code what I have done so far.
var prevSubVarClientId;
jQuery('.mySubscription').select2({
allowClear: true,
placeholder: "",
//minimumInputLength: 3,
ajax: {
type: "POST",
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
delay: 250, // delay in ms while typing when to perform a AJAX search
data: function (params, page) {
return {
action: 'list_posts',
q: params.term,
};
},
processResults: function( data ) {
var options = [];
if ( data ) {
jQuery.each( data, function( index, text ) {
options.push( { id: text['id'], text: text['name'] } );
});
}
return {
results: options
};
},
cache: true
}
});
jQuery('.mySubscription').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.mySubscription').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
var subscriptionId = jQuery($this).data("subscription-id");
var url = jQuery($this).data("ajax-url");
var userId = jQuery($this).val();
jQuery.ajax({
type: "POST",
url: url,
data : {
action : 'update_var_client_user_id',
userId : userId,
subscriptionId : subscriptionId
},
success: function(data)
{
var data = JSON.parse(data);
toastr["success"]("Transferred Successfully." );
}
});
},
function(){
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
As you can see I have prevSubVarClientId variable and mySubscription dropdown with this class.
jQuery('.mySubscription').change(function() { here you can see I am opening alertify confirm box and if I click on "No" then I am doing below code.
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
But then whenever I am trying to open the dropdown again, I am getting the below error.
Can some one guide me, what I am doing wrong here ?
Thanks

"The results could not be loaded". only show when return data is null or not found.
I tested your code below snippet and working fine.
$(".js-data-example-ajax").select2();
jQuery('.js-data-example-ajax').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.js-data-example-ajax').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
console.log('change');
},function(){
console.log('no change');
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
.select2-container, .select2-container--open .select2-dropdown--below {
width: 200px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/css/alertify.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js"></script>
<select class="js-data-example-ajax">
<option value="abc">ABC</option>
<option value="bca" selected>BCA</option>
<option value="mnp">MNP</option>
<option value="pqr">PQR</option>
</select>

Related

alert box not working in ajax success (asp.net)

I'm using ajax call in input box onclick event.
when I call alertbox in ajax success it's not working but console.log is working good.
Please help me.
in my view
<input id="extention" type="text" value="" onkeyup="SetExtention(event, this.value); return false;" class="form-control terminal_id" />
my function
function SetExtention(e, item) {
console.log("SetExtention");
e.preventDefault();
if (item != "") {
if (e.keyCode == 13) { //Enter Event
var inputLine = $('#extention').val().split(',');
if (inputLine.length == 0)
return;
else {
$('#hdnLastExtention').val(inputLine[inputLine.length - 1]);
for (var i = 0; i < inputLine.length; i++) {
$.ajax({
url: urls,
type: 'GET',
dataType: 'json',
data: {
ID: inputLine[i]
},
cache: false,
async:false,
success: function (result) {
alert("aaaaaaaa");
console.log("aaaaaa");
if (result.isSuccess == false) {
doing some work...
}
if ($('#hdnLastExtention').val() == result.inputData)
{
alert("alert box doesn't appear.");
console.log("alert box doesn't appear.");
}
},
error: function (request, error) {
console.log("It has error");
}
});
}
}
}
}
}
Finally, that's the result of console (I attached the image to make clear the results.)
I can see the console log but alert box doesn't work.
Reference Image
This happens when you tick the confirm box for "Stop this page from creating pop-ups".
Do try, close the tab and open a new window and try.
Make sure in the script tag has type="text/javascript" attribute.
eg;
<script type="text/javascript">
// Your function
</script>

fullcalendar - multiple sources to turn off and on

I've a calendar that I want to list various types of event on and enable a checkbox filter to show/hide those kind of events.
Is there a way to say on this action, ONLY load from 1 data-source AND remember that URL on month next/prev links?
I've started using eventSources, but it loads them all, rather than the one(s) I want.. Here's what I have.
var fcSources = {
all: {
url: tournament_url + '/getCalendar/?typefilter=[1,2]'
},
type1: {
url: tournament_url + '/getCalendar/?typefilter=[1]'
},
type2: {
url: tournament_url + '/getCalendar/?typefilter=[2]'
}
};
These URLS all provide a json string of events, based on the types prrovided.
Here's my calendar:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek'
},
firstDay: 1, // Monday = 1
defaultDate: new Date(), // Now
editable: true,
eventSources: [ fcSources.all ],
events: fcSources.all,
nextDayThreshold: '00:00:00',
... etc etc
Above my calendar I have this:
input type="checkbox" name="event_filter[]" value="type1" /> Type 1
input type="checkbox" name="event_filter[]" value="type2" /> Type 2
And finally , two Jquery fucntions.. one to get all the filters:
function getFilters(getName) {
var filters = [];
var checked = [];
$("input[name='"+getName+"[]']").each(function () {
filters.push( $(this).val() );
});
$("input[name='"+getName+"[]']:checked").each(function () {
checked.push( $(this).val() );
});
return [filters, checked];
}
and the last to load them:
$(".event_filter").on('click', function() {
var doFilters = getFilters('event_filter');
$('#calendar').fullCalendar( 'removeEvents' );
if (doFilters[0] === doFilters[1]) {
$('#calendar').fullCalendar( 'addEventSource', fcSources.all );
} else {
$.each(doFilters[1], function(myFilter, myVal) {
console.log(myVal);
$('#calendar').fullCalendar( 'addEventSource', fcSources.myVal );
});
}
// $('#calendar').fullCalendar( 'refetchEvents' );
});
Since the sources are all the same place and just different data on the URL, this approach could meet your needs. In the demo it just alerts the URL that is being tried but doesn't actually supply any data...
https://jsfiddle.net/gzbrc2h6/1/
var tournament_url = 'https://www.example.com/'
$('#calendar').fullCalendar({
events: {
url: tournament_url + '/getCalendar/',
data: function() {
var vals = [];
// Are the [ and ] needed in the url? If not, remove them here
// This could (should!) also be set to all input[name='event_filter[]'] val's instead of hard-coded...
var filterVal = '[1,2]';
$('input[name="event_filter[]"]:checked').each(function() {
vals.push($(this).val());
});
if (vals.length) {
filterVal = '[' + vals.join(',') + ']' // Are the [ and ] needed in the url? If not, remove here too
}
return {
typefilter: filterVal
};
},
beforeSend: function(jqXHR, settings) {
alert(unescape(settings.url));
}
}
});
// when they change the checkboxes, refresh calendar
$('input[name="event_filter[]"]').on('change', function() {
$('#calendar').fullCalendar('refetchEvents');
});
Try this!
$('#calendar').fullCalendar({
events: function( start, end, timezone, callback ) {
var checked = [];
$("input[name='event_filter[]']:checked").each(function () {
checked.push( $(this).val() );
});
var tournament_url = 'https://www.example.com';
$.ajax({
url: tournament_url + '/getCalendar/',
data: {typefilter: '['+checked.join(',')+']'},
success: function(events) {
callback(events);
}
});
}
});
$('input[name="event_filter[]"]').on('change', function() {
$('#calendar').fullCalendar('refetchEvents');
});
This works for me.

Meteor.js calling a template.helpers function vs global variable

I am using Reactive-table to display paginated data in my meteor.js app as shown below, yet data displayed in Reactive-table is dependent on on specific user event (Selecting client, project, date range and clicking on the submit button). So I was wondering if it is possible to trigger template.helpers >> myCollection function from the 'submit form' event? OR is it better to define a global variable to store data returned from user query based on the user (client, project, date range selection) then make this global variable the return from the myCollection function?
I have tried researching how to call .helpers function from an template.events event but couldn't find any information. So any help on which approach is better and if calling the .events function is better then how to do that, will be highly appreciated. Thanks.
Below is the code I have in my app:
Template.detailedreport.rendered = function() {
Session.set("dreport_customer", "");
Session.set("dreport_project", "");
Session.set("dreport_startDate", new Date());
Session.set("dreport_endDate", new Date());
$('.set-start-date').datetimepicker({
pickTime: false,
defaultDate: new Date()
});
$('.set-end-date').datetimepicker({
pickTime: false,
defaultDate: new Date()
});
$('.set-start-date').on("dp.change",function (e) {
Session.set("dreport_startDate", $('.set-start-date').data('DateTimePicker').getDate().toLocaleString());
});
$('.set-end-date').on("dp.change",function (e) {
Session.set("dreport_endDate", $('.set-end-date').data('DateTimePicker').getDate().toLocaleString());
});
};
Template.detailedreport.helpers({
customerslist: function() {
return Customers.find({}, {sort:{name: -1}});
},
projectslist: function() {
return Projects.find({customerid: Session.get("dreport_customer")}, {sort:{title: -1}});
},
myCollection: function () {
var now = Session.get("dreport_startDate");
var then = Session.get("dreport_endDate");
var custID = Session.get("dreport_customer");
var projID = Session.get("dreport_project");
Meteor.call('logSummary', now, then, projID, custID, function(error, data){
if(error)
return alert(error.reason);
return data;
});
}
},
settings: function () {
return {
rowsPerPage: 10,
showFilter: true,
showColumnToggles: false,
fields: [
{ key: '0._id.day', label: 'Day' },
{ key: '0.totalhours', label: 'Hours Spent'}
]
};
}
});
Template.detailedreport.events({
'submit form': function(e) {
e.preventDefault();
var now = $('.set-start-date').data('DateTimePicker').getDate().toLocaleString();
var then = $('.set-end-date').data('DateTimePicker').getDate().toLocaleString();
var custID = $(e.target).find('[name=customer]').val();
var projID = $(e.target).find('[name=project]').val();
//Here is the problem as I am not sure how to refresh myCollection function in .helpers
},
'change #customer': function(e){
Session.set("dreport_project", "");
Session.set("dreport_customer", e.currentTarget.value);
},
'change #project': function(e){
Session.set("dreport_project", e.currentTarget.value);
}
});
Template:
<div>
{{> reactiveTable class="table table-bordered table-hover" collection=myCollection settings=settings}}
</div>
Server:
Meteor.methods({
logSummary: function(startDate, endDate, projid, custid){
//Left without filtering based on date, proj, cust for testing only...
return Storylog.find({});
}
});
Template helpers are reactive, meaning that they will be recomputed if their dependencies change. So all you need to do is update their dependencies and then the myCollection helper will be recomputed.
Replace your comment // Here is the problem... with:
Session.set('dreport_endDate', then);
Session.set('dreport_startDate', now);
Session.set('dreport_project', projID);
Session.set('dreport_customer', custID);

What is the reason behind popup opening only first time

I have a strange problem and i m not able to understand why it is happening.
I called a page - Remarks(say) by jquery ajax on row click of grid viw. Then i binded that page (coming in response) into a div - dvRemarks(say). This div is opening in a popup.
Pop-up window is only opening first time, which is working fine. But when i click second time, data is coming in response, But this time popup is not opening. Problem is with popup only but i don't understand why it is ?
When i again refresh the page, it again opens up Ist time only.
Below is jquery :-
jQuery(function() {
// Remarks
jQuery('#<%=dvRemarks1.ClientID %>').dialog({
autoOpen: false,
width: 600,
modal: true
});
// Remarks Link
jQuery('#lnkDialog').click(function() {
jQuery('#<%=dvRemarks1.ClientID %>').dialog('open');
return false;
});
});
Below is the function which i am calling on click :-
function Call_Ajax(id)
{
var d = new Date();
var n = d.getMilliseconds();
var parameters="id=" + id;
$.ajax({
type: "POST",
url: "Remark.aspx",
data: {id:id, n:n},
success: function(response) {
$('#<%=dvRemarks.ClientID %>').html(response);
$("#lnkDialog").click();
},
error: function() {
alert('Some problem has been occured.');
}
});
}
And below is the div - dvRemarks in which i am binding response
<div id="dvRemarks1" runat="server" style="display: none;" title="Enter Remarks">
<div id="dvRemarks" runat="server">
</div>
</div>
Thanks.
Not sure on this but give a try to below one.
jQuery(function() {
// Remarks
jQuery('#<%=dvRemarks1.ClientID %>').dialog({
autoOpen: false,
width: 600,
modal: true, //Calling destroy on close function might help
close: function() {
$(this).dialog("destroy");
}
});
// Remarks Link
jQuery('#lnkDialog').click(function() {
jQuery('#<%=dvRemarks1.ClientID %>').dialog('open');
return false;
});
});
give a try changing ajax call to
function Call_Ajax(id)
{
var d = new Date();
var n = d.getMilliseconds();
var parameters="id=" + id;
$.ajax({
type: "POST",
url: "Remark.aspx",
data: {id:id, n:n},
success: function(response) {
$('#<%=dvRemarks.ClientID %>').empty().html(response); //empty function may be of some help here
$("#lnkDialog").click();
},
error: function() {
alert('Some problem has been occured.');
}
});
}

jQuery UI Dialog + Validate

I'm having trouble in validating a jQuery UI dialog using Jquery Validate upon clicking Save.
Here's my code to create Jquery dialog. It loads the dialog from a target a href URL:
$(document).ready(dialogForms);
function dialogForms() {
$('a.dialog-form').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.find('#return').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {submitFormWithAjax($(this).find('form'));},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
width: 'auto'
});
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
beforeSend: function(data) {
//alert("beforesend");
form.validate();
},
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'text',
error: function(data) {
alert(data);
$('#result').html(data);
},
success: function(data) {
//alert("success");
$('#result').html(data);
setTimeout("reloadPage()", 500);
}
});
return false;
}
The beforeSend is called, but it doesn't seem to call the validate method, which is located on the parent page from which Dialog is called.
$(document).ready(function() {
$("#event_form").validate({
rules: {
Name: {
required: true
},
Category: {
required: true
}
},
messages: {
Name: "Please enter an event name",
Category: "Please choose a category"
},
submitHandler: function(form) {
alert("validated");
// $('#loading_1').show();
// $('#proceed_c').hide();
// $(form).ajaxSubmit();
// //form.submit();
},
errorPlacement: function(error, element) {
error.appendTo(element.next(".status"));
}
});
}
Is the problem with the beforeSend within submitFormWithAjax function, the location of $("#event_form").validate or the submitHandler: function(form) within it? Any help will be greatly appreciated.
When you initialize the jQueryUI dialog, it modifies the DOM, the whole dialog is taken out of it's location in the page and inserted right before the </body> tag. You can see this with Firebug. This causes a problem for Validate, because now the form is empty. To solve this, on the dialog's open event, append it to the form. It sounds really wacky, but trust me, it works :)
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {submitFormWithAjax($(this).find('form'));},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
open: function(){
$(this).parent().appendTo($('#event_form'));
},
width: 'auto'
});
Edit:
<form id='event_form'>
<div id="dialog" title="DialogTitle">
</div>
</form>
Took a slightly different approach to this. I needed to reuse my modal form so I append it once jquery "creates" the modal:
$("#mdl_Subject").dialog({
autoOpen: false,
show: "drop",
hide: "drop",
modal: true,
create: function () {
$(this).parent().appendTo($('#aspnetForm'));
}
});

Resources