I'm using jQuery to load html content which contains images, the problem is that i don't want the effect of blinking on images due to loading, to achieve that i need to pre load images inside the response body before inserting it to guarantee a smooth update.
Current Code:
$.ajax({
url: 'hello.php',
method: 'GET',
data:'id='+id,
success: function(data) {
$('#section').html(data);
}
});
Any Solutions?
Thanks
I use the the jQuery onImagesLoad plugin for this.
You could try something like this (untested):
var imagesLoading = 0;
$.ajax({
url: 'hello.php',
method: 'GET',
data: 'id=' + id,
success: function(data) {
imagesLoading = 0;
$(data).filter('img').each(function() {
imagesLoading++;
var image = new Image();
image.onload = function() {
imagesLoading--;
if(imagesLoading == 0) {
$('#section').html(data);
}
};
image.src = $(this).attr('src');
});
}
});
Works fine when I tried it.
Related
I use setInterval to update a table every 5 seconds which works great except that it creates a "blinking" effect since the Div refreshes as if I pressed F5.
Is it possible to hide it with example fadeIn() function? I have tried but without any luck so far. Does anyone have any experience with this?
var append_increment = 0;
setInterval(function() {
$("#_change tr").remove();
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {
' tables ': append_increment
}
})
.done(function(response) {
$('#_change').append(response).fadeIn("milliseconds", "linear");
append_increment += 0;
});
}, 5000)
flickering happen because you update the content before the ajax call completes not after it
you can try this
var append_increment = 0;
var Di = setInterval("clearInterval(Di);GetData();", 5000);
function GetData(){
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {' tables ': append_increment}
})
.done(function(response) {
$('#_change tr').html(response).fadeIn(500, "linear");
Di=setInterval("clearInterval(Di);GetData();",5000);
append_increment += 0;
});
}
Also let the html response from server be without <tr></tr>
One thing you can do is make all the changes in memory before issuing a DOM refresh (an expensive process). This can be done with the detach() event:
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {
' tables ': append_increment
}
})
.done(function(response) {
let $table = $('#_change')
let $parent = $table.parent()
$table.detatch()
$table.find('tr').remove();
$table.append(response);
$parent.append($table);
append_increment += 0;
});
}, 5000)
More than likely, it wouldn't solve flickering. For that, a closer example would need to be given. Some of that could be the amount of painting to the screen, some might be the delay of the AJAX. You are removing and creating elements, so a "flicker" is expected -- this is also where a library like React, which uses a virtual DOM, would excel.
There will always be some flicker (most of the time negligible) when content is updated. A way to reduce this even more is to have two tables and as soon as the background table is filled, then swap it to the front and continue exchanging the two views, but is probably unnecessary.
To minimize the flicker time in this case, I would suggest to move the .remove() function into the .done() in the line right before the .append(). Even though code acts fast, sometimes our eyes can see small delays.
This solution should make sure that the data is not being removed until the AJAX call has completed a return. I would also go one step further and check the response to make sure the call returned successfully just for robustness.
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {
' tables ': append_increment
}
})
.done(function(response) {
if (/* response['statusCode'] == 200 */) {
$("#_change tr").remove();
$('#_change').append(response);
append_increment += 0;
}
});
}, 5000)
I want to dynamically change the Ajax URL, this is what I have done so far :
var size=1;
var from = 1;
window.addEventListener('mousewheel', function(e){
if(e.wheelDelta<0 && from<5){
from++;
}
else if(e.wheelDelta>0 && from>1){
from--;
}
console.log(from)
});
$.ajax({
type: 'GET',
url: "/api/v1/users?f="+from+"&s="+size,
data: { get_param: 'value' },
dataType: 'json',
With the mousewheel event I change the value of "from", with this variable I can concatenate the string /api/v1/users?f="+from+"&s="+size, to form a URL.
The variable works fine when I give mousewheel event-listener, but doesn't change the Ajax URL.
Any tips?
Your understanding is not right, your scroll code block change the value of from when scrolling is done. But when page loads the ajax call initiates with the initial value of from.
So to solve this you have to call ajax inside event handler.
If i understand you correctly i think following will help you.
You need to move the ajax call inside the event listner to get the values of from in ajax call
Here is my solution based on the code you provided.
var size = 1;
var from = 1;
window.addEventListener('mousewheel', function(e) {
if (e.wheelDelta < 0 && from < 5) {
from++;
} else if (e.wheelDelta > 0 && from > 1) {
from--;
}
$.ajax({
type: 'GET',
url: "/api/v1/users?f=" + from + "&s=" + size,
data: {
get_param: 'value'
},
dataType: 'json',
success: function() {}
})
});
Here is the scenario:
I am sending ajax request when user click on anchor tag to fecht & update instagram media status.
But it take sometime to retrieve the response, in that time user clicked N number of time on that anchor tag.
So each time it sends the request, I am don't want such behaviour ..
Is there any easy way to handle such situation?
Currently I am adding the class when user clicked on it, and using that I am deciding user has click on anchor tag or not??
Please let me know, if it is correct way or not..
Here is fiddle URL (Not clicked on link at least 2+ times, it send 2+ request which is i don't want )
http://jsfiddle.net/bkvaiude/mxb8x/
thanks
You should use should remove the click event and then set it up again when the ajax call is complete:
Instead of setting it in the success call as the others do; you should use the complete callback to set it. To make sure if the server returns an error it is still binding the click event again.
http://jsfiddle.net/eWwZt/
(function (){
console.log("bhushan");
var ajaxCall = function(e){
$("#test").off("click");
console.log("click");
e.preventDefault();
var is_liked_url = "https://api.instagram.com/v1/media/popular?client_id= b52e0c281e584212be37a59ec77b28d6";
$.ajax({
method: "GET",
url: is_liked_url,
dataType: "jsonp",
success: function(data) {
console.log("data...");
},
complete: function(){
$("#test").on("click", ajaxCall);
}
});
}
$("#test").on("click", ajaxCall);
})();
Put a flag to check if ajax call completed or not this way:
(function (){
var RequestInProgress = false;
console.log("bhushan");
$("#test").on("click", function(e){
e.preventDefault();
if(!RequestInProgress) // if request not in progress send
{
RequestInProgress = true;
var is_liked_url = "https://api.instagram.com/v1/media/popular?client_id= b52e0c281e584212be37a59ec77b28d6";
$.ajax({
method: "GET",
url: is_liked_url,
dataType: "jsonp",
success: function(data) {
console.log("data...");
RequestInProgress = false;
}
});
}
});
})();
UPDATED FIDDLE
You can use .off() to unbind click to element.
(function () {
console.log("bhushan");
var Myfunction = function (e) {
$("#test").off("click"); //Unbind click
e.preventDefault();
var is_liked_url = "https://api.instagram.com/v1/media/popular?client_id= b52e0c281e584212be37a59ec77b28d6";
$.ajax({
method: "GET",
url: is_liked_url,
dataType: "jsonp",
success: function (data) {
console.log("data...");
$("#test").on("click", Myfunction);
}
});
};
$("#test").on("click", Myfunction);
})();
DEMO
try this
var gettingData =false;
$('selector').click(function() {
gettingData = false;
if (!gettingData) {
gettingData =true;
$.ajax(//do ajax logic)
.success(
gettingData = false;
//parse data)
.error(
gettingData = false;
//display some error
);
} else {
return false;
}
});
this is javascript
$(window).scroll(function() {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function my_func () {
//show new name
}
});
});
this is not_data.php
<?php
$name_query=mysql_query("SELECT name FROM names");
while($run_query = mysql_fetch_assoc($name_query)) {
$name = $run_query['name'];
echo $name;
}
?>
i want to call a new ajax request and get a new name from table names everytime user scrolls down
have a look at this excellent jquery plugin!
http://jscroll.com/
jScroll is a jQuery plugin for infinite scrolling, written by Philip
Klauzinski. Infinite scrolling; also known as lazy loading, endless
scrolling, autopager, endless pages, etc.; is the ability to load
content via AJAX within the current page or content area as you scroll
down. The new content can be loaded automatically each time you scroll
to the end of the existing content, or it can be triggered to load by
clicking a navigation link at the end of the existing content.
creat param for check loading state;
bind to scroll event
get two params
var top = $(this).scrollTop();
var height = $(this).height();
check scroll height
if (elHeight - top - height <= 50)
where elHeight - height of all element
and when it's true do your query
Try like this.
$(window).scroll(function() {
if( $(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function (res) {
// new name will be available in 'res' you can display in what way you like.
}
});
}
});
Check If you have reached bottom and load more(send ajax call)
var win = $(window),
doc = $(document);
win.scroll(function(){
if( win.scrollTop() > doc.height() - win.height() ) {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function my_func (name) {
$('<span>').html(name).appendTo('body')
}
});
}
});
Look at this code please - how could I kill / update or restart an ajax call (not content that Ajax calls) after the content has already been called?
I mean the $('#posting_main') is called onclick and animated - how to stop ajax and make it another $('#posting_main') on another click?
$(document).ready(function() {
$("#img_x_ok").click(function(e){
e.preventDefault();
var post_text = $.trim($("#main_text_area").val());
var data_text = 'post_text='+ post_text;
if (post_text === "") return;
var xhr = $.ajax({
type: "POST",
url: "comm_main_post.php",
data: data_text,
cache: false,
success: function (data){
//content
$("#posting_main").fadeIn();
$("#posting_main").load("pull_comm.php");
$("#main_text_area").attr("value", "");
$("#posting_main").animate({
marginTop: "+=130px",
}, 1000 );
}
}); //ajax close
}); }); //both functions close
You can abort the current request with:
xhr.abort();
After having done that, you can run another $.ajax(...) to make a second request.
You could implement it like the following. Note that indenting code makes it a lot more readable!
$(document).ready(function() {
var xhr; // by placing it outside the click handler, you don't create
// a new xhr each time. Rather, you can access the previous xhr
// and overwrite it this way
$("#img_x_ok").click(function(e){
e.preventDefault();
var post_text = $.trim($("#main_text_area").val());
var data_text = 'post_text='+ post_text;
if (post_text === "") return;
if(xhr) xhr.abort(); // abort current xhr if there is one
xhr = $.ajax({
type: "POST",
url: "comm_main_post.php",
data: data_text,
cache: false,
success: function (data){
//content
$("#posting_main").fadeIn();
$("#posting_main").load("pull_comm.php");
$("#main_text_area").attr("value", "");
$("#posting_main").animate({
marginTop: "+=130px",
}, 1000 );
}
});
});
});
I am not sure I fully understand your question, however:
xhr.abort() will kill the AJAX request. After calling abort(), you could modify and resend the request, if desired.
$("#posting_main").stop() will stop the fadeIn animation. (And I think you might need to follow that with $("#posting_main").hide() to be sure it isn't left partially visible.)