Reinitialize jQuerytools Overlay on ajax loaded element - javascript

I am trying to reinitialize a Overlay on new ajax loaded elements.
Here my code:
$('input.search-files').keyup(function(event){
if( event.keyCode == 13 ) {
$.ajax({
type: "GET",
url: ...,
dataType: "html",
data: {...},
beforeSend: function(){
$('.tr-documento').fadeOut('fast', function(){ $(this).remove(); });
$('.table-content').find('.table-loader').show();
},
success: function(data) {
if( $(data).filter('tr').length == 0 ){
$('.table-loader').before( '<tr class="tr-documento"><td colspan="10">Non ci sono</td></tr>' );
} else{
$('.table-loader').before( $(data).filter('tr') );
}
$('.table-content').find('.table-loader').hide();
$("table.table-content").tablesorter({headers: { 0: { sorter: false }, 6: { sorter: false },7: { sorter: false },8: { sorter: false },9: { sorter: false } } });
reInitializeAjaxed();
$(".modifica-file[rel]").overlay();
}
});
}
});
This function is triggered on "ENTER" keyup.
Everything work fine, table sorter works at first hit.
jQuerytools overlay event instead, is binded only at the second hit on "ENTER".
Someone knows this issue?
Is there a way to "live" overlay event and not re-init each ajax call?
I tried this:
$(document).delegate('.modifica-file[rel]', 'load', function(){ $(".modifica-file[rel]").overlay(); });
but is not working..

I think is not opened because the overlay is only initialized without firing.
You can set the load attribute at true like:
$(".modifica-file[rel]").overlay({load: true});
or fire the overlay manually using the load method:
$(".modifica-file[rel]").data("overlay").load();
Docs: http://jquerytools.org/documentation/overlay/
Example: http://jquerytools.org/demos/overlay/trigger.html

I found solution here: http://flash.flowplayer.org/forum/tools/40/21252
There are many solutions on this link, i am using the following:
$(".modifica-file[rel]").live('click', function () {
$(this).overlay().load();
$(this).overlay().load();
return false;
});
I think this is quite dirty solution...$.live() method is not supported anymore on latest jQuery versions...but i am using 1.7.2 and it is working fine!
I added this snippet to end of SUCCESS AJAX callback.

Related

AJAX async:true breaks site on mobile browsers

I am using this function to return search results via AJAX. However, it kills mobile browsers on search. It works if I set it to 'async:false' but this means that I can't have a loading icon.
I cant find anything online to indicate why this would not be working on mobile, when it works fine on desktop.
Any ideas?
(function($) {
$(document).ready(function() {
$("#filter").on('keyup input', function() {
delay(function() {
var input = $('#filter');
var query = input.val();
var content = $('#content')
$.ajax({
type: 'post',
url: myajax.ajaxurl,
async: true,
data: {
action: 'load_search_results',
query: query
},
beforeSend: function() {
input.prop('disabled', true);
content.addClass('loading');
},
success: function(response) {
input.prop('disabled', false);
content.removeClass('loading');
content.html(response);
myPluginsInit();
}
});
return false;
}, 700);
});
});
})(jQuery);
I was able to solve this problem by adding a separate 'loader' div with an ID of loader to my page, and add the loading class to this instead. The code now looks like this:
(function($) {
$(document).ready(function() {
$("#filter").on('keyup input', function(){
delay(function(){
var input = $('#filter');
var query = input.val();
var content = $('#content')
$.ajax({
type : 'post',
url : myajax.ajaxurl,
async: true,
data : {
action : 'load_search_results',
query : query
},
beforeSend: function() {
input.prop('disabled', true);
$('#loader').addClass('loading');
},
success : function( response ) {
input.prop('disabled', false);
$('#loader').removeClass('loading');
content.html( response );
myPluginsInit();
}
});
return false;
}, 700 );
});
});
})( jQuery );
You're problem is still in your keyup input handler. I'm not sure where the function delay is declared (I'm assuming it's some wrapper around setTimeout). However it doesn't really matter.
The issue is that the handler fires for every input and keyup event. The "delay" is inside that. All the "delay" is doing is "waiting" before it makes the ajax call but an ajax call is still being created for every keyup and input event.
This means that a lot of ajax calls are being created and on a mobile platform that's a problem. I'm not exactly certain when (or how often) you need to make the call to the server but to see what I'm talking about just add the line I've included below:
(function($) {
$(document).ready(function() {
$("#filter").on('keyup input', function() {
console.log('handling keyup or input') // add this line and watch them stack up
delay(function() {
var input = $('#filter');
var query = input.val();
var content = $('#content')
$.ajax({
type: 'post',
url: myajax.ajaxurl,
async: true,
data: {
action: 'load_search_results',
query: query
},
beforeSend: function() {
input.prop('disabled', true);
content.addClass('loading');
},
success: function(response) {
input.prop('disabled', false);
content.removeClass('loading');
content.html(response);
myPluginsInit();
}
});
return false;
}, 700);
});
});
})(jQuery);

How to pass $("#MyInputTag").val to my Ajax call and keep that value for later use

How can I send $("#query").val()) using my Ajax function ?
If I put my Ajax call in my $(document).ready(function() , my code doesn't work anymore (the script doesn't start).
=> I can see the 'test123' string on my next page but , but if I type something in my "query" Input_Field, and then click on my link href (pointing to the same location) , the input field is reset and loose my value "query"...
Please help me :( Thank you
$(document).ready(function() {
$("#completed").live('click', function() {
alert($("#query").val());
});
$.ajax ({
url: 'http://localhost:3000/user/updateattribute',
data: { chosenformat: 'test123' , query: $("#query").val() } ,
type: 'POST',
success: function()
{
alert ('success ' );
return false; }
});
});
// do not use this anymore $(document).ready(function() {
$(function() {
event.preventDefault();
// live is no longer used use on..
$("#completed").on('click', function() {
console.log($("#query").val());
// alerts are annoying learn to use console
});

jQuery AJAX triggering too quickly

I have a relatively simple jQuery AJAX call wrapped in a function and I am testing my error functionality. The problem I am facing is the AJAX call happens too quickly! It is causing my 'H6' and '.loading' elements to start repeating. The behaviour I require is to remove the elements, then call the ajax.
function getAvailability(form) {
var str = $(form).serialize(),
warning = $('#content h6');
if ( warning.length > 0 ) {
$(warning).remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
}
else
{
$('<div class="loading">Loading…</div>').insertAfter(form);
}
$.ajax({
type: "POST",
url: "someFile",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$('<h6>Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
});
}
});
return false;
}
I would love to sequence it like so -> Remove 'warning' from page, add .loading. Then trigger AJAX. Then fade out .loading, add & fade in warning/calendar dependent on success.
I have amended my original code, and I have got the function to behave as expected, primarily because I have disabled the submit button during the ajax process.
function getAvailability(form) {
var str = $(form).serialize(),
btn = $('#property_availability');
// Disable submit btn, remove original 'warning', add loading spinner
btn.attr("disabled", "true");
$('.warning').remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
$.ajax({
type: "POST",
url: "public/ajax/returnAvailability1.php",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$(this).remove();
$('<h6 class="warning">Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
btn.removeAttr("disabled");
});
}
});
return false;
}
I believe that the original sequence was not working as expected due to the time delay created by the fadeOut() functions.
Instead of adding and removing warning, why not just show/hide leveraging ajaxStart and ajaxStop?
warning.ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).fadeOut();
});
If you need to sequence your events, then you should try using the deferred and promise methods that are a part of the jQuery.ajax API. This article does a good job of introducing them: http://www.bitstorm.org/weblog/2012-1/Deferred_and_promise_in_jQuery.html

jQuery plugin bsmSelect doesn't update its values when it is called again and its select options have changed

I'm using bsmSelect jQuery plugin. Basically, what it does is changing the way a select-multiple is rendered to make easier to pick up the options. It hides the select element and shows a list instead.
So, first of all I'm applying the plugin function to my select-multiple element:
$(document).ready(function() {
...
$('#my_select_multiple').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
...
});
On the other way, I have another select element (this one is simple) which has an ajax request bind to its change event. This ajax request get new #my_select_multiple options depending on the select simple value. Ajax response is the new HTML for #my_select_multiple options. So I have:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/
}).responseText;
return r;
}
...
$(document).ready(function() {
...
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val()));
}
...
});
AJAX is working as expected. New options are got correctly and they are inserted into #my_select_multiple (which is hidden by bsmSelect plugin, but I can check it with Firebug). But bsmSelect didn't realize new changes and doesn't get updated.
So, I think what I want is to reapply $('#my_select_multiple').bsmSelect(); with its new options.
I've been looking around a little bit and here is what I have tried.
1. I've tried to call again the funcion with the success and complete (one at time) of the AJAX request. Didn't work:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function() { $('#my_select_multiple').bsmSelect(); }
}).responseText;
return r;
}
2. I've tried to bind the function with the on jQuery function. Didn't work:
$('#my_select_simple').on('change', function() {
$('#my_select_multiple').bsmSelect();
});
3. I've tried 1 and 2 removing previosly the HTML generated by bsmSelect. Didn't work.
Thank you very much.
UPDATE: The exact code
First I have a global.js file which apply bsmSelect plugin to some select multiples (.quizzes):
$('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
And then, in the php file I define the updateQuizzes function and bind it to the select simple (project_id) change event:
<script type="text/javascript">
function updateQuizzes(project_id) {
var r = $.ajax({
type: 'GET',
url: '<?php echo url_for('event/updateQuizzes')?>'+'<?php echo ($form->getObject()->isNew()?'':'?id='.$form->getObject()->getId()).($form->getObject()->isNew()?'?project_id=':'&project_id=')?>'+project_id,
success: function() { $('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
}); }
}).responseText;
return r;
}
$('#project_id').change(function(){
$('.quizzes').html(updateQuizzes($(this).val()));
});
</script>
As I told, the AJAX request works without problems, but not the calling bsmSelect the second time...
Not sure if this is what the problem is, but you could try
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val())).trigger('change');
}
This triggers a change event on select_multiple, and might fire bsmSelect. I'm not sure what the problem here is exactly, but that's the best I can come up with.
I think you want to set your HTML in the success of the Ajax call, something like:
function loadNewOptions(val) {
$.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).bsmSelect();
}
});
}
And then calling like:
$('#my_select_simple').change() {
loadNewOptions($(this).val());
}
$(document).ready(function() {
$('#my_select_simple').change() {
$('#my_select_multiple').load("your Url", function(){
$('#my_select_multiple').bsmSelect();
});
}
});
something like this should work.
.load will put whatever your url returns into #my_select_multiple
the first parameter is the url to load, and the 2nd is a function to call when it is done. which is where you need to set up your fancy selector.
Ok, I opened a ticket and bsmSelect developer has answered me in minutes. Great!
To let bsmSelect know about its select changes, you have to trigger a change event on the select. There is no need to call bsmSelect again.
So it can be that way:
function loadNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).trigger('change');
}
}).responseText;
return r;
}
$('#my_select_simple').change(function() {
loadNewOptions($(this).val());
});

jQuery.ajax not working in IE7/8

Something in my script is breaking IE.
I'm looking on a collection of links with a class, and hijacking the URL's.
Clicking a link will animate the height and reveal a message. It also
does an ajax request to mark the message as read.
However, in IE it simply goes to the URL instead of staying on the page and processing the http request.
$('.message .subject .subject_link').click(function(e) {
toggle_message(e)
return false;
});
function toggle_message(m) {
var link = m.target;
var parent = $(link).parent().parent();
console.log(link.href);
$.ajaxSetup({
url: link.href,
dataType: 'json',
timeout: 63000,
type: 'GET',
cache: false
});
if($(parent).hasClass('unread')) {
$(parent).addClass('read').removeClass('unread');
$.ajax({
complete: function(r, textStatus) {
console.log(r.responseText)
}
});
}
if($(parent).find('.body_wrapper').hasClass('collapsed')) {
$(parent).find('.body_wrapper').addClass('expanded').removeClass('collapsed');
$(parent).find('.body_wrapper').animate({
height: 'toggle'
})
} else {
$(parent).find('.body_wrapper').addClass('collapsed').removeClass('expanded');
$(parent).find('.body_wrapper').animate({
height: 'toggle'
})
}
}
any ideas what's causing this issue?
http://support.cooper.krd-design.net/
tester: 12345 if you want to review the page
Thanks
Rich
Adding
e.preventDefault();
before toggle_message in the first function should work, although return false should as well.
I don't have access to IE right now but I think you could try preventing the default click event to fire in your click()-function like so:
$('.message .subject .subject_link').click(function(e) {
toggle_message(e)
e.preventDefault();
});
More on .preventDefault() here: http://api.jquery.com/event.preventDefault/

Categories