prevent calling ajax multiple times - ajax

I am trying to figure out ways to prevent ajax from being called multiple times. Below is my code. I created a scrollable div, my goal is, once the scroll inside this div is about to reach the bottom, I want to call the ajax. Everything works so far. But the problem is, whenever I scroll the div fast enough to the bottom, the ajax is being called multiple times.
$('.scroll_div').scroll(function(){
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){
}
}).done(function(data){
alert(data);
});
}
});

I would put a timer on it - adjust the timeout accordingly, so that the ajax would only fire if the user stays put for a second or two:
$('.scroll_div').scroll(function(){
if(typeof(myTimer)!='undefined'){
clearTimeout(myTimer);
}
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
//timer
myTimer = window.setTimeout(function(){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){}
}).done(function(data){
alert(data);
});
}, 2500);
}
});

Related

Ajax not working propperly on first click

I have this of code that will show the data on a modal when a button click :
$("#editItem").on('show.bs.modal', function(e) {
$("#editAlert").attr("class", "d-none");
$("#editNoChanges").attr("class", "d-none");
var serialNo = $(e.relatedTarget).data('item-id');
console.log(serialNo); //Serial Key
$(e.currentTarget).find('input[name="productSerialEdit"]').val(serialNo);
$.ajax({
type: 'POST',
url: 'getItemInfo.php?serialNo='+serialNo,
data: {
serialNo: serialNo
},
dataType: 'json',
success: function(edit) {
var trig = "edit";
var nameEdit = $("#productNameEdit option[value='"+edit[0]+"']").prop('selected', true);
var typeEdit = $("#productTypeEdit option[value='"+edit[1]+"']").prop('selected', true);
var locEdit = $("#productLocationEdit option[value='"+edit[2]+"']").prop('selected', true);
$("#productPriceEdit").attr("value", edit[3]);
populateSelect(trig, nameEdit, typeEdit, locEdit);
console.log("Editting ..");
console.log($(nameEdit).val());
console.log($(locEdit).val());
console.log($('#productPriceEdit').val());
}
});
});//Edit Funtion End
the problem is that, on first click, its not showing the right data, i have to click the button/show the modal 2nd time to show the correct data, what could be the problem or solution for this ?

Can't post ajax value

Still stack in these code. On any browser desktop working fine, but when try use chrome on my android, can't post value from ajax datastring.
jQuery(document).ready(function()
{
jQuery(".button").click(function()
{
var product = jQuery(".products").val().split('|')[0];
var nomortujuan = jQuery(".nomortujuan").val();
var pn = parseFloat(document.getElementById("val[pin]").value);
var dataString = 'method=sendMessage&message='+product+'.'+ nomortujuan+'.'+pn;
var web = 'ajax.php';
jQuery.ajax ({
type: "POST",
url: web,
data: dataString,
cache: true,
beforeSend: function(html) {
document.getElementById("hasil").innerHTML = '';
jQuery(".flash").show();
jQuery(".flash").html('<div style="float:left;"></div>');
},
success: function(html){
jQuery("#js_process_request input, #js_process_request select").attr('disabled',false);
jQuery(".flash").hide();
jQuery("#hasil").hide();
jQuery ("#hasil").append(html);
return false;
}
});
});
});
Maybe this problem
jQuery ("#hasil").append(html);
remove spacing to fix it
jQuery("#hasil").append(html);

How to animate AJAX post?

sorry for this request but I'm an AJAX beginner.
I have the following script and I'm trying to animate it (something like "fade").
jQuery(document).ready(function($){
$(document).on("click",".ratingemo", function(){
var rating = $(this).attr("id").substr(0, 1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&rating="+rating;
$.ajax({
type: "POST",
url: "/ldplug/rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
How can I do that?
Many thanks!
First of all live is deprecated, check out on instead. But that being said, why not:
success: function(e){
$("#r"+id).hide();
$("#r"+id).html(e).fadeIn("slow");
}
It would be better to just have $("#r"+id) hidden to start, I just hid it to illustrate the point.
Without seeing your HTML, I have to assume that something like this will work for you. Hide the element, populate it, then fade it in.
jQuery(document).ready(function ($) {
$(".ratings").live("click", function () {
var rating = $(this).attr("id").substr(0, 1);
var id = $(this).attr("id").substr(1);
var data = "id=" + id + "&rating=" + rating;
$("#r" + id).hide();
$.ajax({
type: "POST",
url: "/ratings/rate.php",
data: data,
success: function (e) {
$("#r" + id).html(e);
$("#r" + id).fadeIn();
}
})
});
});

Ajax Codeigniter form doesn't work in IE?

This is the ajax code for the form submission:
$('form[class^="ajaxsubmit_"]').live('submit', function(e){
e.preventDefault();
var classname = $(this).attr('class');
var classnamesplit = classname.split("_");
var container = classnamesplit[1];
if (container == 'parent'){
container = $(this).parent();
}
$(container).show();
$(container).html('<img src="public/images/web/ajax.gif"/>');
$(this).ajaxSubmit(container);
});
(function($){
jQuery.fn.ajaxSubmit =
function(container) {
var url = $(this).attr('action');
$.ajax({
url: url,
type: "POST",
data: $(this).serialize(),
dataType: "html",
success: function(msg) {
$(container).html(msg);
}
});
return this;
};
})(jQuery);
This is like a general function for all forms, it reads the action and sends the data to it. Then outputs in the parent or the specified div. It works perfectly fine in Chrome, Firefox and Opera. How can I solve this?

Synchronised Ajax requests with JQuery in a loop

I have the following situation: I need to make synchronized Ajax requests within a loop and display the returned result after each iteration in a div-element (appended on top with the previous results at the bottom). The response time of each request can be different but the order in which it should be displayed should be the same as issued. Here is an example with 3 requests. Lets say request "A" needs 3 seconds, "B" needs 1 second and "C" needs 5 seconds. The order I want to display the result is A, B, C as the requests were issued but the code I use shows the results in B, A, C.
Here is the code (JQuery Ajax request):
$(document).ready(function(){
var json = document.getElementById("hCategories").value;
var categories = eval( '(' + json + ')' );
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
$("#content").append(data);
}
});
});
I thought it would work with "async:false" but then it waits until every Ajax call is finished and presents the results after the loop. I hope some of you can point out some different solutions, I am pretty much stuck.
Thanks in advance,
Cheers Chris
EDIT: Thanks for all the possible solutions, I will try these now one by one and come back with that one that fits my problem.
I have two solution proposals for this problem:
Populate generated divs
You could generate divs with ids in the loop and populate them when the request finishes:
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
for (curCat in categories) {
(function(curCat) {
var curCatKey = categories[curCat]['grKey'];
$('#content').append('<div id="category-"' + escape(curCat) + '/>');
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val()),
success: function(data) {
$("#category-" + escape(curCat)).html(data);
}
});
})(curCat);
}
});
Or use a deferred
You can store jqXHR objects in an array and use a deferred to call the success functions in order, when all calls have finished.
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
var requests;
for (curCat in categories) {
var curCatKey = categories[curCat]['grKey'];
requests.push($.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val())
}));
}
$.when.apply(requests).done(function() {
for (i in requests) {
requests[i].success(function(data) {
$("#content").append(data);
});
}
});
});
The first method has the advantage that it populates the containers continuously. I have not tested either of these function, but the logic should work the way I described it.
This would do the trick
var results = [];
var idx = 0;
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
(function( i ) {
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
results[i] = data;
if (i == idx - 1) { // last one
for (var j=0; j < results.length; j++) {
$("#content").append(results[j]);
}
}
}
});
})(idx++);
I think something like this is what you're looking for. Might need some tweaking, I'm a little rusty on Deferred. Read up on it though, mighty powerful
deferred = $.Deferred()
for(curCat in categories) {
deferred.pipe(
function(resp){
postData = {} // set up your data...
return $.post("get_results.php", {data: postData, timeout: 8000})
.done(function(content){ $("#content").append(content) })
})
)
}
// Trigger the whole chain of requests
deferred.resolve()

Resources