jQuery and AJAX: how to deal with too fast responses? - javascript

I've done a web page that has to make the use wait a loooong time before getting the answer.
When the user clicks on "Generate" (complex stuff), i do a slow slideUp() of the main div and immediately after that, I launch my "background" AJAX call:
$('#div-lol-generate-result').slideUp(4000);
$('#div-lol-generate-form').slideUp(3000);
$.ajax({
url: '/long/api/call/that/takes/between/1/and/10/seconds',
data: data,
dataType: 'json',
method: 'POST'
})
.done(function(result) {
console.log('ok :');
console.log(result);
var monp=$('<p />');
if (typeof(result.error)!='undefined') {
for (var i in result.error) {
monp.append(result.error[i]);
monp.append('<br />');
}
} else if (typeof(result.story)!='undefined') {
console.log(result.story.length);
for (var i in result.story) {
monp.append(result.story[i]);
monp.append('<br />');
}
}
monp.last().remove();
$('#div-lol-generate-result').empty().append(monp).slideDown();
});
})
.error(function(result) {
console.log('Erreur :');
console.log(result);
})".
Everything works fine... only when the answer takes longer than the "hide" animation. If the answer is fast, the we can see the content of the maindiv being replaced.
How do you deal with that?

You make sure both the animation and the ajax call has completed before you replace the content
var promise1 = $('#maindiv').slideUp(4000).promise();
var promise2 = $.ajax({
url : '/complexstuff',
data : data,
dataType : 'json',
method : 'POST'
});
$.when.apply($, [promise1, promise2]).done(function(elem, data) {
$('#maindiv').html(data.result).slideDown();
});
This way the ajax call starts right away without having to wait for a callback, and the promises makes sure both have completed before the callback for $.when is called.

Here's my final working code, thanks to adeneo
$(document).ready(function() {
$('#div-lol-generate-result').hide();
var sub=function() { return lol_submit(); };
var lol_submit = function() {
var data=$('#lol-generate-form').serialize();
$('#lol-generate-form :input')
.prop('disabled', 'disabled');
$('#lol-generate')
.unbind('click')
.click(function(e) {
e.preventDefault();
});
$.when(
$('#div-lol-generate-result').slideUp(4000),
$('#div-lol-generate-form').slideUp(3000),
$.ajax({
url: '/lol/json/story',
data: data,
dataType: 'json',
method: 'POST'
})
)
.then(function(a, b, c) {
result=c[0];
var monp=$('<p />');
if (typeof(result.error)!='undefined') {
for (var i in result.error) {
monp.append(result.error[i]);
monp.append('<br />');
}
}
else if (typeof(result.story)!='undefined') {
console.log(result.story.length);
for (var i in result.story) {
monp.append(result.story[i]);
monp.append('<br />');
}
}
monp.last().remove();
$('#div-lol-generate-result')
.empty()
.append(monp)
.slideDown();
}, function(a, b, c) {
/* should never happen
* TODO: hide and all ask refresh
*/
// a=xhr
// b='failure'
// c='Not Found'
})
.always(function(result) {
$('#lol-generate-form :input').removeAttr('disabled');
$('#lol-generate').click(sub);
$('#lol-generate-form-input-summoner-name').focus().select();
$('#div-lol-generate-form').slideDown();
});
return false;
}
$('#lol-generate-form').submit(sub);
$('#lol-generate').click(sub);
});

Related

Add ajax to existing page with jquery-ui

I need help with an advanced search I implemented into a new existing page system.
It seems there is a problem with the existing jquery ui on the page:
<script src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="js/jquery.lazy.min.js"></script>
When I enter my code the page isn't working properly anymore.
My code:
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#warenkorb_suche_feld').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#warenkorb_suche_feld').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#warenkorb_suche_feld").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
The search script works fine but I need to add
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And after this page stops working. What can I do to get this stuff working?
Consider the following. I was not able to test it.
$(function() {
function search(term, callback) {
$('b#search-string').text(term);
$.ajax({
type: "POST",
url: "search.php",
data: {
query: term
},
cache: false,
success: function(html) {
$("ul#results").html(html);
if(callback && (typeof callback == "function")){
callback();
}
}
});
return false;
}
$('div.icon').click(function() {
$('input#warenkorb_suche_feld').focus();
});
$("input#warenkorb_suche_feld").on("keyup", function(e) {
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string.length > 0) {
$("ul#results, h4#results-text").fadeOut(400, function() {
search(search_string, function() {
$("ul#results, h4#results-text").fadeIn();
});
});
}
});
});
This makes use of the complete callback for .fadeOut(). So once it has faded, it will then run the search. I added a Callback in the search so that once the AJAX has completed, it will reveal the results with .fadeIn().
You may want to consider adjusting the length condition. This ensures

Ajax Iterate - Repeat the AJAX Call every 3 seconds

AJAX call instead of .click load - I would like the ajax to run every 3 seconds till the end of Total_Records. Here is my AJAX code which runs .click of a button.
I am passing two variables
1. id number
2. Total_Records
I would like the ajax to iterate a number of times = Total_Records.
Any suggestions are highly appreciated.
$(document).ready(function() {
$(document).on('click', '.show_more', function() {
var ID = $(this).attr('id');
var lim = $(this).attr('Total_Records');
$.ajax({
type: 'POST',
url: 'moreajax.php',
data: {
'id': ID,
'lim': lim
},
success: function(html) {
setTimeout(function() {
$('#show_more_main' + ID).remove();
$('.postList').append(html);
}, delay);
},
});
});
});
Method 2) Please kindly read and recommend any better way or script improvement with examples please. this will benefit everyone.
Note: I believe this method would be a great enhancement and re-usable to lots of people who are looking for interval runs.
The only issue is the cancel button .click is not stopping the ajax call.
$('#cancel').click(function() {
cancel = true;
});
$(function() {
//If cancel variable is set to true stop new calls
if (cancel == true) return;
var RecordsInterval = 10 * 1000;
var fetchRecords = function() {
console.log('Sending DATA AJAX request...');
$.ajax({
type: "POST",
url: "fetchRecords.php",
data: {
'id': ID,
'lim': lim
}
}).done(function(html) {
$('#show_more_main' + ID).remove();
$('#postList').append(html);
alert("You got it champ")
console.log('success');
console.log('Waiting ' + (RecordsInterval / 1000) + ' seconds');
setTimeout(fetchRecords, RecordsInterval);
}).fail(function() {
console.log('error');
alert("error Champ");
return;
});
}
// Fetch Records immediately, then every 10 seconds AFTER previous request finishes
fetchRecords();
});

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)

Open window after script execution

Is it possible to open the window after the execution of the script expandNextLevel()?
I'm asking this because I don't want to let the client see the expand/collapse animation but just the treeview collapsed.
This is my code.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel();
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel();
collapseNextLevel();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
Regards
try this
$.when(expandNextLevel()).done(function(){
/// show window
});
docs https://api.jquery.com/jquery.when/
I think the fastest way to do something like this is put everything in a hidden div, wich you will then show when you're done with the code execution.
You could also put a visible div with a rotating icon while the code is being executed, and hide it when you show the main content to make the users know something is happening.
EDIT:
I made a slight modification to the expand function, that should let me know when it's done executing the recursion, by adding an index I increment everytime. At the end of the function there is a code that will be executed only when the index is equal to one, wich means the first instance of the function is done executing.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel(0);
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel(var i)
{
i++;
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel(i);
collapseNextLevel();
}
if (i == 1)
{
$.("#maincontent").show();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
You should put you content inside a div
<div id="maincontent" style="display:none;">
/*your content*/
</div>
I didn't test it but it should work :)
There is a better way to do this with jQuery.when, jQuery.done and promises, but I'm not confident I can give you a working sample since I never used those methods

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

Categories