I have a bootstrap tooltip that I want to load data from an AJAX requestion, with the text from the request being the title
property of the tooltip. My AJAX request works fine, but I have two problems:
ttManager
object to encapsulate the tooltip's state?Currently, when the page first loads and I click on #btnSubmit
in the console I see
success
and the correct data from the console.log(ttManager) line
$(document).ready(function () {
//this object's title attribute will be the value of ttManager.title seen below
var ttManager = {
title: '',
setTitle: function (data) {
this.title = data;
}
}
var ajaxCall = function () {
//this returns the top five results of text from a query
$.ajax({
type: "POST",
contentType: "application/json",
url: "Service.asmx/GetDrugs",
dataType: "json",
success: function (data) {
console.log('success');
ttManager.title = data.d;
//inside this function I want to set ttManager.title equal to the data.d
console.log(ttManager);
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
}
$('#btnSubmit').tooltip({
//reference to ajax call
//title is the attribute responsible for displaying text in the tooltip
//I need to use a reusable object to set the text property instead of referencing ajaxCall
//would it be better if there below were title: ttManager.title?
title: ajaxCall,
trigger: 'click',
placement: 'right'
});
});
I'm pretty sure that I need a callback function somewhere, but I'm not sure where. Any future pointers would be appreciated, too. Thanks.
First, a little explanation of bootstrap's tooltip plugin. The tooltip displayed will pull from the elements title
attribute if there's one present, otherwise it will use the title argument passed.
The next thing you need to understand is that ajax calls are asynchronous. This means code will continue to run while it's waiting for a response. So, for example, if I do something like this
$.ajax({
URL: 'google.com',
success: function(){
console.log('yay');
}
});
console.log('woohoo');
you'd see "woohoo" in the console before "yay". So, currently, you're calling $('#btnSubmit').tooltip
before your ajax query has altered the state of ttManager.
The other issue is that you're currently not doing anything with ttManager in relation to bootstrap. I feel like I should also mention that the ttManager object seems meaningless here.
Personally, I would change my ajax success function to this (sets the title attribute, calls tooltip, then produces another click to make the tooltip appear)
success: function(data) {
$('#btnSubmit').attr('title', data.d)
.tooltip({
trigger: 'click',
placement: 'right'
}).click();
}
remove the current $('#btnSubmit').tooltip...
code currently there, and add in a one time click handler to call your ajax.
$('#btnSubmit').one('click', function() {
ajaxCall();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With