Ajax query not working after page is reloaded - ajax

I have 2 ajax query as below, and both the ajax query is working on the initial page loading, after loading data using 1st AJAX query the 2nd ajax query does not work after the page content is loaded, so request your help and advice as to home to resolve this issue such that both the ajax query works after every page load.
Ajax Query : 1
<script type="text/javascript">
$(document).ready(function(){
$("input[type='radio']").on('click', function(){
var radioValue = $("input[name='Gender']:checked").val();
var surl = '/fdata/' + radioValue;
var dsurl = encodeURI(surl, "UTF-8");
var hurl = '/Summary';
var dhurl = encodeURI(hurl, "UTF-8");
if (radioValue == "Male" ) { $('#DGender').load('dsurl #DGender'); };
if (radioValue == "Female" ) { $('#DGender').load('dsurl #DGender'); };
if (radioValue == "Summary" ) { $('#DGender').load('dhurl #summary'); };
});
});
</script>
Ajax Query : 2
<script type="text/javascript">
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('input[type=search]').val('');
$('#DGender thead tr').clone(true).appendTo( '#DGender thead' );
$('#DGender thead tr:eq(1) th').each( function (i) {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+'" />' );
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
var table = $('#DGender').DataTable( {
ordering: false,
orderCellsTop: true,
fixedHeader: true,
filter: false,
searching: true,
info: false,
paging: false,
scrollX: "80vh",
scrollCollapse: false
});
} );
</script>
From,
Vino

Related

Borwser's back button state update after ajax call

I am trying to sort out back and forward browser buttons in my ajax page load setup.
This is my ajax code that calls page content:
jQuery(document).ready(function () {
$ = jQuery;
$("body").on("click", ".menuAjax a", function (e) {
//On click on body for ajax calls
e.preventDefault();
var pageID = $(this).data("id");
var catType = $(this).data("type");
var pageTitle = $(this).data("title");
var footerAdSwitch = $("#overFooter").data("footeradswitch");
var homePageSet = parseInt($("#homePageSet").val());
var $this = $(this);
//console.log($this);
var res;
var payload = JSON.stringify({
action: "router_loader",
pageid: pageID,
footeradswitch: footerAdSwitch,
homepage: homePageSet,
cattype: catType,
pagetitle: pageTitle,
});
XHR = $.ajax({
type: "get",
url: my_ajax_object.ajax_url + '/' + payload + '/view_' + (pageID || catType),
beforeSend: function () {
$("#ajaxPageLoader").show();
},
complete: function () {
$("#ajaxPageLoader").hide();
},
success: function (res) {
if (res != "") {
$("#ajaxpageLoad").html(res);
setTimeout(function () {
$("#ajaxPageLoader").hide();
}, 600);
$(".nav li.menu-item").removeClass(
"current-menu-item current_page_item"
);
$($this).parent().addClass("current-menu-item current_page_item");
const nextURL = $this[0].href;
history.pushState(res, pageTitle, nextURL);
document.title = pageTitle + " - company name";
$.getScript("/wp-content/themes/customTpl/js/functions.js");
var lazyLoadInstance = new LazyLoad({
threshold: 200,
});
$("html, body").animate({ scrollTop: 0 }, 0);
} else {
$("#ajaxPageLoader").hide();
}
},
error: function (req, status, error) {},
});
});
//Exclude expander btn from ajax call
$("body").on("click", ".btnNoBorder, .mobileMenueBtn, .closeBtn", function (e) {
e.stopPropagation();
});
window.addEventListener('popstate', function(e) {
$("#ajaxpageLoad").html(res);
updateContent(e.state);
});
});
Right now I ma stuck with popstate function, which I would like to pass urls of current position, so they are remembered once a users presses back button.
Can someone suggest me direction as to how to update history navigation with the browser buttons ?

Prevent sorting on clicking Input Field in Data Table not working

I am using DataTable to display my Data.
Issue
Each Column has a Search Field in the Head. But when I click on the input field, it keeps sorting every time I click inside the input field.
This is what I need
On Clicking, I don't want the sorting through input box.
What I have tried isn't working
<script type="text/javascript">
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example thead th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
var table = $('#example').DataTable({
"pageLength": 20,
initComplete: function () {
this.api().columns().every( function () {
var that = this;
$( 'input', this.header() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that.search( this.value ).draw();
}
});
} );
}
});
} );
</script>
Please help.
To do this you can use 2 rows in the header:
the first one to control ordering/sorting
another one to display each input field
Then you need to use the orderCellsTop option to specify that only the first row should be used to control sorting.
A basic example, would therefore be as follows:
$(document).ready(function() {
$("#result-table thead tr").clone(true).appendTo("#result-table thead");
// add a text input filter to each column of the new row
$("#result-table thead tr:eq(1) th").each(function (i) {
var title = $(this).text();
$(this).html("<input type='text' class='form-control' placeholder='Search '" + title + "' />");
$("input", this).on( "keyup change", function () {
if ($("#result-table").DataTable().column(i).search() !== this.value) {
$("#result-table").DataTable().column(i).search(this.value).draw();
}
});
});
$('#example').DataTable({
orderCellsTop: true,
});
} );

Load more posts with AJAX and also add pagination in URL

On load more button, posts load without page load using AJAX, but wanted to implement Wordpress pagination on load more along with URL changing. Suggestions are welcome.
/* Category/tag page Masonry Grid */
var $mgrid = $( '.post-grid' ).masonry();
$mgrid.masonry( {
itemSelector: '.post-outer',
} );
/* ------------------ Load More Posts Category/tag page ------------------ */
$( document ).on( 'click', '#post-button', function(e) {
e.preventDefault();
var offset = $( this ).attr( 'data-value' );
var cat = $( this ).attr( 'data-cat' ); //load more button attribute
var tag = $( this ).attr( 'data-tag' ); //load more button attribute
var page = $( this ).attr( 'data-page' ); //load more button attribute
var $content;
$.ajax( {
type: "post",
async: false,
dataType: "json",
url: localizeObj.ajaxurl, //localize script in functions.php
data: {
action: 'fetch_posts', //ajax load more function in functions.php
offset: offset,
cat: cat,
tag: tag,
page: page,
search_term: localizeObj.search_term,
current_page: localizeObj.current_page
},
beforeSend: function() {
},
success: function(response) {
/* Adding page numbers on ajax load more */
var pathname = window.location.pathname;
if ( response.success == 'yes' ) {
$content = $(response.posts);
$( '.post-masonry-grid' ).append( $content ).masonry( 'appended', $content );
page = parseInt(page) + 1;
offset = parseInt(offset) + 6;
$('.post-grid-outer').each( function() {
$('.post-grid-outer').addClass(offset);
});
$( '#post-grid-button' ).attr( 'data-value', offset );
$( '#post-grid-button' ).attr( 'data-page', page );
var page_num = '';
if(page <= 2) {
var page_num = 'page/'+ page;
} else {
var page_num = page;
}
window.history.pushState("URL", "Title", page_num); // Add page numbers to URL
} else {
$( '#post-button' ).hide();
}
},
complete : function() {
}
} );
} );

infinite scroll + isotope

I need help: I use isotope with infinite scroll to display thumbnails for a gallery. Everything works when all items are displayed (without isotope filter). By cons, when one uses the isotope filter (that is to say at the opening of my page), animation to view thumbnails runs for all new elements even those that should be filtered !
In short: we see animation bits for each new item loaded, it expands and then shrinks, becoming opaque and hides, creating sparkles ...
How to disable and hide the animation from the beginning each new element that should be filtered?
Thanks for your help ! (sorry for my English)
/*Masonry*/
var $containermasonry = $('.masonry');
$containermasonry.imagesLoaded( function() {
$containermasonry.masonry({
itemSelector: '.item',
});
$containermasonry.isotope({
transitionDuration: '0.8s',
animationEngine: 'best-available',
itemSelector : '.item',
layoutMode : 'masonry',
filter : '.new',
getSortData: {
date: '[data-date]',
categories:'[data-categ]',
}
});
});
/*infinitescroll*/
$containermasonry.infinitescroll({
navSelector : '#page-nav',
nextSelector : '#page-nav a',
itemSelector : '.item',
loading: {
finishedMsg: '',
img: '_include/img/supersized/progress.gif'
}
},
function( newElements ) {
var $newElems = $( newElements ).css({'display': 'none', 'visibility': 'hide', opacity: 0});
$newElems.imagesLoaded(function(){
/*$newElems.animate({ opacity: 1 });*/
$containermasonry.infinitescroll('retrieve');
$containermasonry.masonry( 'appended', $newElems, true );
$containermasonry.isotope( 'appended', $newElems, true );
});
}
);
// filter items
var $optionSets = $('#options .option-set'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function(){
var $this = $(this);
if ( $this.hasClass('selected') ) {
return false;
}
var $optionSet = $this.parents('.option-set');
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
var filterValue = $(this).attr('data-option-value');
$containermasonry.isotope({ filter: filterValue });
});
It is difficult to answer well without a jsfiddle or link.
The big issue is that you are using calling masonry.js and isotope.js at the same time! They are two separate plugins, not designed to be used together. Isotope has a masonry layout which is where your confusion lies, it is not called with masonry.js. Choose one or the other.
Also, if your using isotope v2, animationEngine has been removed from that version.
Here is the code you should use for isotope use:
var $containermasonry = $('.masonry');
$containermasonry.imagesLoaded( function() {
$containermasonry.isotope({
transitionDuration: '0.8s',
itemSelector : '.item',
layoutMode : 'masonry',
filter : '.new',
getSortData: {
date: '[data-date]',
categories:'[data-categ]',
}
});
});
//infinitescroll
$containermasonry.infinitescroll({
navSelector : '#page-nav',
nextSelector : '#page-nav a',
itemSelector : '.item',
loading: {
finishedMsg: '',
img: '_include/img/supersized/progress.gif'
}
},
function( newElements ) {
var $newElems = $( newElements ).css({'display': 'none', 'visibility': 'hide', opacity: 0});
$newElems.imagesLoaded(function(){
//$newElems.animate({ opacity: 1 });
$containermasonry.infinitescroll('retrieve');
$containermasonry.isotope( 'appended', $newElems, true );
});
}
);
// filter items
var $optionSets = $('#options .option-set'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function(){
var $this = $(this);
if ( $this.hasClass('selected') ) {
return false;
}
var $optionSet = $this.parents('.option-set');
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
var filterValue = $(this).attr('data-option-value');
$containermasonry.isotope({ filter: filterValue });
});

Ckeditor Get Content From Iframe

I have a iframe and i'm trying to use Dialog to get data in Iframe and output to current html, but i don't know how to get Ckeditor Content from the Iframe.
I tried to using CKEDITOR.instances['editor'].getData(); but look like cannot get it.
This is my code:
<textarea class='editor' name='description' id='description'></textarea>
$( "#dialog_custom" ).dialog({
autoOpen: false,
modal: true,
height: 768,
width: 1024,
buttons: {
Add: function() {
var model = $('.dialog_custom').contents().find('#model').val();
var product_id = $('.dialog_custom').contents().find('#product_id').val();
var product_name = $('.dialog_custom').contents().find('#product_name').val();
var qty = $('.dialog_custom').contents().find('#qty').val();
var total = $('.dialog_custom').contents().find('#total').val();
var category = $('.dialog_custom').contents().find('#category').val();
if(qty=='') { qty = '0'; }
if(total=='') { total = '0.00'; }
if(model=='') {
alert('Please input the correct Model Number.');
} else {
$(".product").append(InsertTableGetFromIframe);
$('.delete_custom_row').click(function() {
if(confirm("Are you sure want to delete this data?")) {
$(this).parents('.custom_row').next('.parts_row').remove();
$(this).parents('.custom_row').remove();
}
});
$('.dialog_custom').contents().find('#model').val('');
$('.dialog_custom').contents().find('#product_id').val('');
$('.dialog_custom').contents().find('#product_name').val('');
$('.dialog_custom').contents().find('#qty').val('');
$('.dialog_custom').contents().find('#total').val('');
$('.dialog_custom').contents().find('#category').val('');
$(this).dialog("close");
i++;
}
},
Close: function() {
$(this).dialog("close");
}
}
});
$( "#open_custom" ).click(function() {
$( "#dialog_custom" ).dialog( "open" );
});
</script>
Finally, I found out the solution to get the content in the iframe, i used jquery to submit the form then POST the value on the field and get it by Jquery again.
It's the most simple way that i found, actually I think we have another way better to do it...

Resources