jQuery, apply .buttonset to an element that's not yet loaded - ajax

I have the following code working nicely:
$field2.on("change", "#selector", function(){
$field2.load("./index.php?show-options=true", { value: $(this).val() }, function() {
$("#options").buttonset();
});
});
It loads the #options div and applies button to anchor tags within it.
Is there a way to declare
$("#options").buttonset();
BEFORE the #options div is loaded?
I looked through jQuery docs with no success, and also found this answer:
Apply jQuery UI widgets to ajax loaded elements
which I think might be on track, but haven't understood it fully nor managed to implement.
Help appreciated, thanks.

Doing the following:
$field2.on("change", "#selector", function(){
$field2.load("./index.php?show-options=true", { value: $(this).val() }, function() {
$field2.find("#options").buttonset();
});
});
Will make all option elements within $field2 into a button set (once the content has been updated).
Or alternatively you could make the button set on dom ready:
$(function() { $("#options").buttonset(); });
Update
jQuery selectors work on elements in the DOM (unless given a context), if the element is not in the DOM then unfortunately jQuery will not be able to affect it directly. If the load then call to buttonset is causing a FOUC (flash of unstyled content), you could try the following:
$field2.on("change", "#selector", function() {
$field2.empty();
$.get("./index.php?show-options=true", { value: $(this).val() }, function(data) {
var newContent = $(data);
$("#options", newContent).buttonset();
$field2.empty().append(newContent);
});
});

Related

Bootstrap load AJAX content in Inactive Tab

I'm building a site utilising Bootstrap tabs and AJAX. I've set it up so that when a link with the class of .load is clicked the content of that html document is loaded into the active tab, in this case #tab2.
This is done using the following:
$(function(){
$("#tab2").delegate('.load', 'click', function (e) {
e.preventDefault();
$("#tab2").load($(this).attr("href"));
});
});
I also need some links in #tab2, those with the class of .load-tab1 to load content into #tab1, which I have achieved with the following code.
$(function(){
$("#tab2").delegate('.load-tab1', 'click', function (e) {
e.preventDefault();
$("#tab1").load($(this).attr("href"));
});
});
The problem is I can't work out how to make it so that when .load-tab1 links are clicked the active tab is also switched from #tab2 to #tab1.
Any help would be greatly appreciated!
UPDATE:
I was able to get it working with the following code but still thinking there is a better solution.
$(function(){
$("#tab2").delegate('.load-tab1', 'click', function (e) {
e.preventDefault();
$("#tab1").load($(this).attr("href"));
$(".tab2").removeClass("active");
$(".tab1").addClass("active");
$(".tab-content #tab2").removeClass("active");
$(".tab-content #tab1").addClass("active");
});
});
You should select the tab in the .load() callback:
$(function(){
$("#tab2").delegate('.load-tab1', 'click', function (e) {
e.preventDefault();
$("#tab1").load($(this).attr("href"), function(response, status, xhr){
$( theFirstTabAnchorSelector ).tab('show');
});
});
});

Loading Content Via Ajax

Ok, so I'm pretty new to ajax and loading content externally and would appreciate any insight to my problem.
I currently have a hidden div that is empty where the ajax content should load in after a link is clicked.
<div id="#ajax-wrap"></div>
I currently have a list of links that all have the same class and I'd like to have, when clicked, the blank div do a slide toggle and then load in the content from the page that the link was to.
Link:
Current jQuery:
$("a.home-right").click(function () {
$('#ajax-wrap').slideToggle();
});
Being as I'm new to Ajax and loading the external content, I'd like to know how to load content from the linked page that's house in the #content tag. So essentially, I'd like a .home-right link, #ajax-wrap would slide toggle, and then Ajax would pull content from the linked page (which is always going to be a different random link) and it's #content div, placing that content in #ajax-wrap.
Thanks in advance for any help folks!
You want to set the ajax for the links. Requirements:
Writing a handler for links.
We must cancel the default behaviour of browser when somebody click on a link (that redirect to the page).
Removing old data ajax recieved from server and make the #ajax-wrap fresh.
Load the remote page via ajax and set it to #ajax-wrap.
Now slide it down.
// Document Ready
$(function () {
// attaching click handler to links
$("a.home-right").click(function (e) {
// cancel the default behaviour
e.preventDefault();
// get the address of the link
var href = $(this).attr('href');
// getting the desired element for working with it later
var $wrap = $('#ajax-wrap');
$wrap
// removing old data
.html('')
// slide it up
.slideUp()
// load the remote page
.load(href + ' #content', function () {
// now slide it down
$wrap.slideDown();
});
});
});
You can simply use the ajax like this:
$("a.home-right").click(function () {
$.ajax({
type: "get",
url: "YOUR URL HERE",
success: function(data){
$('#ajax-wrap').html(data);
$('#ajax-wrap').slideToggle();
},
error: function(){
alert("An error occured");
}
});
});
try this:
$(function(){
$("a.home-right").click(function () {
$('#ajax-wrap').slideUp();
var url = $(this).attr("href")
$.ajax({
type: "get",
url: url,
success: function(msg){
$('#ajax-wrap').html(msg)
$('#ajax-wrap').slideDown();
},
error: function(){
alert("An error occured");
}
});
})
})
Use get:
// Inside click handler
$.get('url_that_returns_data')
.done(function(response){
var $response = $(response);
$('#ajax-wrap').html($response.find('#content')).slideToggle();
});

jQuery UI Ajax Tabs Loading not showing

I'm using jQuery UI Vertical Tabs and the content is loaded via AJAX. I tried almost everything from posts around here, and nothing helped me so far .. :/
I want to display a css3 loading animation placed in <div id="loading-image">...</div>. So far almost nothing is happening.
My code
$(function() {
$( "#messages_tabs_div" ).tabs({
beforeLoad: function( event, ui ) {
console.log(ui);
ui.jqXHR.error(function() {
ui.panel.html("Couldn't load your messages. Try refreshing your page."+
" If you think this is bug you can help us by submitting it at bugs#go-out-sport.com " );
});
ui.jqXHR.complete(function(response){
console.log(response);
});
},
disabled: [6],
select: function(event, ui) {
alert('ASDAD');
}
}).addClass( "ui-tabs-vertical ui-helper-clearfix" );
$( "#messages_tabs_div li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );
});
//jQuery MINE
$(document).ready(function(){
$('#loading-image').hide();
//Set loading bar for all ajax requests
$('#loading-image').bind('ajaxStart', function(){
alert('AJAXXX');
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
$('#loading-image').bind('tabsselect', function(event, ui) {
alert('TABSSSSS');
$(this).show();
}).bind('tabsload', function(event, ui) {
$(this).hide();
});
});
The only thing I get is the AJAX alert. I tried removing $('#loading-image').hide(); and the loading was always there.
Please help ....
Thank you in advance
I recommend to use a global ajax loading..
$(document).ajaxStart(function() {
$("#loading").fadeIn(200);
}).ajaxStop(function() {
$("#loading").fadeOut(300);
}).ajaxSuccess(function() {
});
but, if you want personalize for multiple events, see this questions:
How to call .ajaxStart() on specific ajax calls
jQuery should I use multiple ajaxStart/ajaxStop handling

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

Adding JQuery to content loaded with AJAX

I just learned that you can use live() instead of bind() to make sure an event handler still exists after content is reloaded with AJAX... but what can I do with other added JQuery, such as .sortable()? I have a UL that I need to reload after sorting or adding; but after the AJAX reload, the sorting doesn't quite work right...
It doesn't completely lose the sortability, but the dragging become much more difficult; it will jump around and seemingly switch 2 other sections that's not the one I'm trying to drag. This only happens after the partial reload; my guess is that when it reloads, I need to re-attach the sortable... how can I do this? Here's my code:
$("#sections").sortable({
start: function (event, ui) {
startIndex = ui.item.index();
},
update: function (event, ui) {
$.ajax({
type: "POST",
url: "/Form/sortSections",
data: {
formID: '#(Model.formID)',
displayOrder: ui.item.index() + 1,
sectionID: $(ui.item).attr("id"),
startDisplayOrder: startIndex + 1
},
success: function (result) {
$.get("/Form/_AllSections/#(Model.formID)", function (data) {
$("#sections").html(data);
});
},
error: function (req, status, error) {
alert(error);
}
});
}
});
Use the load event with live() so that it runs every time the element is added to the DOM.
http://api.jquery.com/load-event

Resources