javascript async request blocks user interaction - javascript

I have got a 2d map for a game and every time the user moved the map, new data is reloaded from the server. While the (asynchronous!) ajax request is loading, every user interaction with the map is ignored. So if i want to move the map and do a mousedown -> mousemove -> mouseup, these events are just ignored.
I tried it both with jQuery 1.5.1 and 1.6.4.
My code:
$map_outer.mousedown(function(e) {
e.preventDefault();
engine.map.mouse_down_coords = {x: e.pageX, y: e.pageY};
engine.map.mouse_is_down = true;
engine.map.mouse_down_offset = $map.offset();
}).mouseup(function(e) {
if (!engine.map.mouse_is_down) return;
$.ajax({
type: 'post',
data: {
//...
},
success: function(data) {
//....
},
dataType: 'json',
async: true
});
engine.map.mouse_is_down = false;
}).mouseleave(function() {
engine.map.mouse_is_down = false;
}).mousemove(function(e) {
e.preventDefault();
if (!engine.map.mouse_is_down) return;
//... move the map
});
Why does this block the browser for some hundred milliseconds? (sometypes 300ms on localhost!)
Thanks in advance,
levu

Related

How to catch end of html manipulations in KendoGrid after read()?

I have KendoGrid and want to detect end of all manipulations (including manipulations with html) after read(). How can I catch this event?
I have tried to use RequestEnd event with type "read", but after catching this event Kendo changes some html code in page.
Update after adding databound
I have KendoSortable, binded to KendoGrid, which contains column with positions. After position changes (onChange function), I need to block page (showLoader func) and update positions. As positions have changed, grid data (column with positions) must be reload by read(). And AFTER read() I need to unblock page by hideLoader. So, now, if I don't unbind onDataBound, my page is unblocked after remove/insert.
function onDataBound(e) {
if (ir == 0) {
updatePostion();
}
else {
hideLoader();
}
ir++;
}
function onChange(e) {
var grid = $("#TestQuestionAnswerList").data("kendoGrid");
grid.unbind("dataBound");
var newIndex = e.newIndex;
var dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
grid.bind("dataBound", onDataBound);
showLoader();
updatePostion();
}
function updatePostion() {
if (#Model.Type == 3) {
var positions = [];
grid._data.forEach(function (entry) {
positions.push(entry.ID);
});
var dataToPost = { positions: positions, questionID: #Model.ID };
$.ajax({
url: '#Url.Action("ChangePositions", "Testing")',
type: 'POST',
data: JSON.stringify(dataToPost),
datatype: 'json',
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
grid.dataSource.read();
},
error: function () {
hideLoader();
alert("error");
}
});
}
else {
grid.dataSource.read();
}
}

Animation effect before ajax call

I've watched several tutorials on how to load content without having to refresh the browser. I'm also using history pushState and popstate to update the url dynamically depending on what site that is displaying. However even if this code works, I would like to be able to make som page transition animation effects > call the Ajax function > then make some fadeIn animation effects. So far i've had no luck in trying to do so. I tried to read up on Ajax (beforeSend: function(){}), but the success function seems to execute before the (beforeSend) function. Is there anyone that could point me in the right direction, or tell me what i possibly am doing wrong? I'd appriciate it!
$(document).ready(function() {
var content, fetchAndInsert;
content = $('div#content');
// Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
}
});
};
// User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});
$('.buttonlink').click(function(){
var href = $(this).attr('href');
// Manipulate history
history.pushState(null, null, href);
// Fetch and insert content
fetchAndInsert(href);
return false;
});
});
Questions? Just ask!
Thanks beforehand!
/// E !
You need to use callbacks. The provided solutions will work, but not necessarily sequentially. $.animate() and $.ajax both run asynchronously. If unfamiliar with this term, here's a good intro: http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027
Here's what I might do:
fetchAndInsert = function(href) {
$('#some-element').animate({'opacity':'0.0'}, 1000, function () {
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
content.html(data);
content.animate({'opacity':'1.0'}, 1000);
}
});
});
};
That will fade out whatever is currently in content, fetch the new data, replace what's currently in content, and then fade back in.
I tried to read up on Ajax (beforeSend: function(){}), but the success
function seems to execute before the (beforeSend) function
You can wait for animation to complete before appending new content to html using .queue(), .promise(), .finish()
beforeSend: function() {
element.queue(function() {
$(this).animate({/* do animation stuff */:500}, {duration:5000}).dequeue()
});
},
success: function(content) {
element.finish().promise("fx").then(function() {
container.append(content).fadeIn()
})
}
var element = $("#loading").hide();
var container = $("#content");
var button = $("button");
var ajax = {
// do asynchronous stuff
request: function() {
return new $.Deferred(function(d) {
setTimeout(function() {
d.resolve("complete")
}, Math.random() * 5000)
})
},
beforeSend: function() {
element.fadeIn().queue(function() {
$(this).animate({
fontSize: 100
}, {
duration: 2500
}).dequeue()
});
},
success: function(content) {
element.finish().promise("fx").then(function() {
element.fadeOut("slow", function() {
$(this).css("fontSize", "inherit");
container.append(content + "<br>").fadeIn("slow");
button.removeAttr("disabled")
})
})
}
}
button.click(function() {
$(this).attr("disabled", "disabled");
$.when(ajax.beforeSend()).then(ajax.request).then(ajax.success)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="loading">loading...</div>
<div id="content"></div>
<button>load content</button>
jsfiddle https://jsfiddle.net/ajmL5g1a/
Try this:
fetchAndInsert = function(href) {
// Before send ajax. Do some effects here
$.ajax({
url: 'http://localhost:8000/phpexample/content/' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data) {
// After loading. Do some effects here
content.html(data);
}
});
};
My solution:
fetchAndInsert = function(href) {
var timeBeforeAnimation = Date.now(), animationDuration = 500;
/* Do some animation, I assume that with jQuery,
so you probably know how much time is takes - store that
time in variable `animationDuration`. */
/* Run your "before" animation here. */
$.ajax({ ...,
success: function(data) {
/* Check, if request processing was longer than
animation time... */
var timeoutDuration = animationDuration -
(Date.now() - timeBeforeAnimation);
/* ...and if so, delay refreshing the content,
and perform the final animation. */
setTimeout(function() {
content.html(data);
/* Perfom final animation. */
}, Math.max(0, timeoutDuration);
}
});
};
I would probably try using some css for this.
#content {
opacity: 0;
transition: all 1s;
}
#content.fade-in {
opacity: 1;
}
...
const content = $('#content');
const btn = $('.buttonlink');
const success = data =>
content.html(data).addClass('fade-in');
const fetchAndInsert = url =>
$.ajax({ url, cache: 'false' }).done(success);
const getData = function(e) {
e.preventDefault();
content.removeClass('fade-in');
fetchAndInsert($(this).attr('href'));
};
btn.on('click', getData)

Firing a function every x seconds

I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds

simple ajax request with interval

I recently began learning Ajax and jQuery. So yesterday I started to programm a simple ajax request for a formular, that sends a select list value to a php script and reads something out of a database.
It works so far!
But the problem is, that when I click on the send button, it starts the request, 1 second later. I know that it has something to do with my interval. When I click on the send button, I start the request and every second it requests it also, so that I have the opportunity, to auto-refresh new income entries.
But I'd like to have that interval cycle every second, but the first time I press the button it should load immediately, not just 1 second later.
Here is my code:
http://jsbin.com/qitojawuva/1/edit
$(document).ready(function () {
var interval = 0;
$("#form1").submit(function () {
if (interval === 0) {
interval = setInterval(function () {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}, 1000);
}
return false;
});
});
Thanks!
I might be something like the following you're looking for.
$(document).ready(function () {
var isFirstTime = true;
function sendForm() {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}
$("#form1").submit(function () {
if (isFirstTime) {
sendForm();
isFirstTime = false;
} else {
setTimeout(function () {
sendForm();
}, 1000);
}
return false;
});
});
So, use setTimeout when the callback has finished as setInterval just keeps running whether or not your callback has finished.
$(function () {
$("#form1").submit(postData);
function postData() {
var url = "tbladen.php",
data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
setTimeout(postData, 1000);
}
});
return false;
}
});
Kind of related demo

Adding Gritter Message After Second Deletion

I'm trying to find out why when a user is deleted by clicking on the ajax-delete class icon and performs the deletion process it shows the gritter message after deletion however if you were to immediately delete another user afterwards it removes the previous gritter message but doesn't show another for that second deletion. Any ideas on why this could be?
EDIT: I have figured out that the issue belongs to the $.gritter.removeAll(); code line. When there is another existing notification it removes it but doesn't add the next notification.
Any ideas what I should do here?
var rowToDelete = null;
var basicTable = null;
var api_url = null;
$(document).ready(function() {});
$(document).on('click', '.ajax-delete', function(e)
{
console.log(basicTable);
e.preventDefault();
//defining it like this captures and optimizing the need to cycle over the DOM more than once
//in subsequent calls to the element specifically
$elem = $(this);
$parentElem = $elem.closest('tr');
rowToDelete = $parentElem.get(0);
api_url = $elem.attr('href');
runConfirmation($('td:eq(1)', $parentElem).text());
});
function runConfirmation(nameSting)
{
$mymodal = $('#myModal');
$('.modal-body p', $mymodal).html('Are you sure you want to delete this <strong>'+nameSting+'</strong>?');
$mymodal.modal('show');
}
$('#myModalConfirm').on('click', function(e) {
$.ajax({
type: 'post',
url: api_url,
data: { _method: 'DELETE' },
dataType: 'json',
success: function(response) {
$.gritter.removeAll();
var className = 'growl-danger';
if (response.status == "SUCCESS") {
className = 'growl-success';
basicTable.fnDeleteRow(basicTable.fnGetPosition(rowToDelete));
rowToDelete = null;
api_url = null;
}
$.gritter.add({
position: 'top-right',
fade_in_speed: 'medium',
fade_out_speed: 2000,
time: 6000,
title: response.title,
text: response.message,
class_name: className,
sticky: false
});
}
});
$('#myModal').modal('hide');
});
Replace the following line:
$.gritter.removeAll();
With
$('.gritter-item-wrapper').remove();

Categories