Run WordPress ajax function only if div is visible - javascript

I have an AJAX function running in Wordpress to fetch 5 of the latest posts, but I would like to run this function only when the user scrolls to a point on the page where a specific div is visible - is this possible using jQuery?
My code so far looks like…
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'get_latest', // the PHP function to run
},
success: function(data, textStatus, XMLHttpRequest) {
jQuery('#posts-load').html(''); // empty an element
jQuery('#posts-load').append(data); // put our list of links into it
}
});

You should use waypoints.
var waypoint = new Waypoint({
element: document.getElementById('#matching_div'),
handler: function(direction) {
// your ajax call
}
})
Waypoints library is available here:
http://imakewebthings.com/waypoints/

Related

JQuery & Ajax disable click

I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});

JS, jQuery not working when I refresh part of page with Ajax

I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});

jquery mobile autocomplete , to show message while searching

I am using jquery mobile auto complete , Please see the demo at http://jsfiddle.net/Q8dBH/11/.
So whenever user press any letter,i need to show some message like "please wait."
So i added some code like below.But its showing only 1st time or 2nd time or not showing at all some times..How to show message whenever user types something until server responds back with data.
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
my full js is below.
$(document).on("pagecreate", ".ui-responsive-panel", function () {
$(document).on("click", "li", function () {
var text = $(this).text();
$(this).closest("ul").prev("form").find("input").val(text); });
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length >0) {
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then(function (response) {
$.each(response, function (i, val) {
html += "<li data-role='collapsible' data-iconpos='right' data-shadow='false' data-corners='false'><h2>Birds</h2>" + val + "</li>";
});
$ul.html(html);
//$ul.listview("refresh");
//$ul.trigger("updatelayout");
$('.ui-responsive-panel').enhanceWithin();
});
}
});
});
Working example: http://jsfiddle.net/Gajotres/Q8dBH/12/
Now this is a complex question. If you want to show jQuery Mobile AJAX loader there's one prerequisite, AJAX call must take longer then 50 ms (jQuery Mobile dynamic content enhancement process time will not get into account). It works in jsFiddle example but it may not work in some faster environment.
You can use this code:
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
beforeSend: function() {
// This callback function will trigger before data is sent
setTimeout(function(){
$.mobile.loading('show'); // This will show ajax spinner
}, 1);
},
complete: function() {
// This callback function will trigger on data sent/received complete
setTimeout(function(){
$.mobile.loading('hide'); // This will hide ajax spinner
}, 1);
$.mobile.loading('hide'); // This will hide ajax spinner
},
data: {
q: $input.val()
}
})
beforeSend callback will trigger AJAX loader and complete callback will hide it. Of course this will work only if AJAX call lasts more then 50ms. Plus setTimeout is here because jQuery Mobile AJAX loader don't work correctly when used with web-kit browsers, it is a triggering workaround.

Function.prototype.apply: Arguments list has wrong type

The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.

jQuery: How to apply a function to all elements including some which are loaded later via Ajax?

I have a simple jQuery function that resizes text areas, and I want it to apply to all text areas.
For the most part, this works great:
$(document.ready(function(){$("text_area").resizer('250px')});
However, because it is only called once when the document is ready, it fails to catch text areas that are later added onto the page using Ajax. I looked at the .live() function, which seems very close to what I'm looking. However, .live() must be bound to a specific event, whereas I just need this to fire once when they're done loading (the onLoad event doesn't work for individual elements).
The only thing I can get working is a really obtrusive inclusion of the JavaScript call directly into the Ajax. Is that the recommended way to be doing this?
Edit: Here is the rails source code for what it does for Ajax requests:
$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
var link = $(this);
if (!allowAction(link)) return false;
if (link.attr('data-remote') != undefined) {
handleRemote(link);
return false;
} else if (link.attr('data-method')) {
handleMethod(link);
return false;
}
});
// Submits "remote" forms and links with ajax
function handleRemote(element) {
var method, url, data,
dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
if (element.is('form')) {
method = element.attr('method');
url = element.attr('action');
data = element.serializeArray();
// memoized value from clicked submit button
var button = element.data('ujs:submit-button');
if (button) {
data.push(button);
element.data('ujs:submit-button', null);
}
} else {
method = element.attr('data-method');
url = element.attr('href');
data = null;
}
$.ajax({
url: url, type: method || 'GET', data: data, dataType: dataType,
// stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: function(xhr, settings) {
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
return fire(element, 'ajax:beforeSend', [xhr, settings]);
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
},
complete: function(xhr, status) {
element.trigger('ajax:complete', [xhr, status]);
},
error: function(xhr, status, error) {
element.trigger('ajax:error', [xhr, status, error]);
}
});
}
So in my particular case, I've got a link, that has data-remote set to true, which points to a location that will return JavaScript instructing a form containing a text area to be appended to my document.
A simple way to do this would be to use ajaxComplete, which is fired after every AJAX request:
$(document).ajaxComplete(function() {
$('textarea:not(.processed)').resizer('250px');
});
That says "every time an AJAX request completes, find all textarea elements that don't have the processed class (which seems to be added by the resizer plugin -- terrible name for its purpose!) and call the resizer plugin on them.
You may be able to optimise this further if we could see your AJAX call.
Generally speaking, I would do it this way..
$.ajax({
type : "GET",
url : "/loadstuff",
success: function(responseHtml) {
var div = $("#containerDiv").append(responseHtml);
$("textarea", div).resizer("250px");
}
});
Wondering if you could use .load for this. For example:
$('text_area').load(function() {
$("text_area").resizer('250px');
});

Categories

Resources