Disabling window resize when AJAX query active - javascript

I have a jQuery script that is a search script but also contains functionality to resize an element to the (screen height - 40px) when the window is resized. However, I want to disable the resizing function when a search (AJAX query) is active. Does anyone know how I can do this?
My current code is:
$(document).ready(function(){
$(window).resize(function(){
if($(window).height()<1200){
$("#a").height($(window).height()-40);
}
});
$("form").submit(function(a){
a.preventDefault();
if($("#i").val().length>0){
$.ajax({
type:"get",
url:"search.php?q="+q,
dataType:"html",
success:function(a){
...
}
})
}
})
})

Use .on() and .off()
$(document).ready(function(){
function started(){
if($(window).height()<1200){
$("#a").height($(window).height()-40);
}
$(window).on("resize.name_space",started);
$("form").submit(function(a){
a.preventDefault();
if($("#i").val().length>0){
$(window).off("resize.name_space");
$.ajax({
type:"get",
url:"search.php?q="+q,
dataType:"html",
success:function(a){
$(window).on("resize.name_space",started); ...
}
})
}
})
})

var loading;
...
if($(window).height()<1200 && !loading){
...
loading = true;
$.ajax({
...
complete: function(){
loading = false;
}.
})
}
})

Try this, it adds a check in whilst the ajax is running and will stop the re-sizing from taking place
$(document).ready(function(){
//Create the variable
var check = false;
$(window).resize(function(){
//Is the ajax currently running? This if statement runs if the answer is no
if (check == false && $(window).height()<1200 ) {
$("#a").height($(window).height()-40);
}
});
$("form").submit(function(a){
a.preventDefault();
//Set the variable to true, this stops the resizing above ^^
check = true;
if($("#i").val().length>0){
$.ajax({
type:"get",
url:"search.php?q="+q,
dataType:"html",
success:function(a){
...
},
complete: function() {
//Set back to off once the ajax has finished
check = false;
}
})
}
})
})

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

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)

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

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);
});

Reinitialise JScrollPane after AJAX post loading

Im'm loading posts in a div #reviewspostscont, the AJAX code works and the posts are loaded when the scrollbar gets to the end but I can't reinitialise JScrollPane to show them.
I tried different codes but nothing works, this is what i have so far.
Thanks in advance, Matt
jQuery(document).ready(function($) {
$(function()
{
$('#reviewspostscont').each(
function()
{
$(this).jScrollPane(
{
horizontalDragMaxWidth : 100
}
);
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind(
'resize',
function()
{
if (!throttleTimeout) {
throttleTimeout = setTimeout(
function()
{
api.reinitialise();
throttleTimeout = null;
},
50
);
}
}
);
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight)
{
var count = 2;
if (isAtRight == true) {
loadArticle(count);
var api = $(this).data('jsp');
api.reinitialise();
count++;
}
}
);
}
)
});
function loadArticle(pageNumber){
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop-reviews',
success: function(html){
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});
You can use autoReinitialise. Here's a demo showing a similar example. And another one. And another.

jquery .on() is not triggering

I have the following code:
console.log($(".resultLike"));
$(".resultLike").on("click", function (event) {
alert('test');
event.stopPropagation();
alert('test1');
value['clicked'] = 1;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'removed') {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('Favourite?');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('Login to add');
} else {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('un-Favourite');
}
}
});
});
My expectations is that when you click on the div resultLike, then it will preform the function(). However, it does nothing. I have two alert() calls in there, and neither is being called. The output of console.log() is as follows:
[
<div class=​"resultLike searchBarGameLike">​</div>​
]
That proves it's being put on the page. Any help would be appreciated, thanks.
EDIT:
I think it should be mentioned that I'm actually using two .on() events.
This is actually all my code. The issue is around the
$("body").on("click", ".resultLike", function(){
Line, it's not working.
$searchedGamesContainer.on(
"click",
".box",
function(event){
if(!$displayLock){
$displayLock = true;
var description;
var user_id;
if($(this)[0].style.width == '75%'){
var org_img = $(this).children(".resultInside").find("img").attr("src");
$(this).children(".resultInside").append("<img src='"+org_img+"' id='imgId'/>");
$(this).children(".resultInside").css('height','auto');
$(this).css('width', '18%');
$(this).css('height', 'auto');
$(this).find(".resultData").fadeOut('fast');
setTimeout(function(){$searchedGamesContainer.masonry('reload');},300);
setTimeout(function(){$displayLock = false;},1000);
}else{
var me = this;
var pos;
largeImage= new Image();
value['name']=$(me).find("p").html();
oldImage = $(this).find("img").attr("src");
for(var i = 0; i<$searchBarGames.length; i++){
if($searchBarGames[i][5] == value['name']){
pos = i;
break
}
}
description = $searchBarGames[pos][2];
$(me).find("img").hide();
largeImage.src = $searchBarGames[pos][4];
$(me).find("img").attr("src",largeImage.src);
$(me).children(".resultInside").css('height','400px');
$(me).css('width', '75%');
$(me).children(".resultInside").html("\
<div class='resultData'>\
<div class='resultImg'><img src='"+ largeImage.src +"'></div>\
<div class='resultName'>" + value['name'] + "</div>\
<div class='resultDesc'>" + description +"</div>\
<div class='wikiLink searchBarGameWiki'><a href='http://wikipedia.org/wiki/" + value['name'] + "'>Wikipedia</a></div>\
<div class='resultLike searchBarGameLike'></div>\
</div>");
value['clicked']=0;
$.ajax({
url:'scripts/php/userProfile.php',
data:{action:value},
type: 'post',
dataType: 'json',
success:function(profileData){
//logic
}
});
console.log($(".resultLike"));
$("body").on("click", ".resultLike", function(){
alert('test');
event.stopPropagation();
alert('test1');
value['clicked']=1;
$.ajax({
url:'scripts/php/userProfile.php',
data:{action:value},
type: 'post',
dataType: 'json',
success:function(profileData){
//logic
}
});
}
);
}
}
}
);
try
$("body").on("click", ".resultLike", function(){
// your code goes here.
});
Your implementation will likely not be bound if the div.resultLike is added dynamically
This problem actually ended up being completely because of CSS.
For the div element I wanted the alerts on, I had markup to look like a button.
However, I noticed this:
.resultLike:active {
position:relative;
top:1px;
z-index:1235;
}
I'm not 100% why, but I think this was actually changing where the button was when clicking it. Meaning as soon as it was active, it wasn't where your mouse was. I could be wrong, but this fixed it.

Categories