I don't have a lot of JS experience but I am trying to call an API on a mouse over event, so that I can display some user information in a Bootstrap popover.
I am almost there, however my popover is not displaying, as the function is simply not being called after the Ajax code finishes.
function getUserProfile(email){
return $.ajax({
url: my_url email,
method: 'GET',
data: data,
success: function (data){
console.log(data); // this works ok and we get data back
return data; // we get to here ok
},
async: true
});
}
$(".my-link-popup").off('mouseover').on('mouseover', function (){
getUserProfile(this.href).then(
function(x){
console.log(x) // we don't get to here at all
$(this).popover({
html: true,
title: "<span>x.displayName</span>",
content: "Some nice content"
});
$(this).popover('show');
}
)
})
Where am I going wrong?
CodePudding user response:
In the end it looks like the function was working, but it didn't like the $(this).
This works:
function getUserProfile(email){
return $.ajax({
url: my_url email,
method: 'GET',
data: data,
success: function (data){
console.log(data); // this works ok and we get data back
return data; // we get to here ok
},
async: true
});
}
$(".my-link-popup").off('mouseover').on('mouseover', function (){
let context = this; //added this line
getUserProfile(this.href).then(
function(x){
console.log(x)
$(context).popover({
html: true,
title: "<span>x.displayName</span>",
content: "Some nice content"
});
$(context).popover('show');
}
)
})
CodePudding user response:
The function has its own context
so this
may be of the function so either use arrow function notation or you can use variable to reference outside context with self
.
$(".my-link-popup").off('mouseover').on('mouseover', function () {
let self = this;
getUserProfile(this.href).then((x) => {
console.log(x) // we don't get to here at all
$(self).popover({
html: true,
title: "<span>x.displayName</span>",
content: "Some nice content"
});
$(self).popover('show');
})
});
$(".my-link-popup").off('mouseover').on('mouseover', function () {
getUserProfile(this.href).then((x) => {
console.log(x) // we don't get to here at all
$(this).popover({
html: true,
title: "<span>x.displayName</span>",
content: "Some nice content"
});
$(this).popover('show');
})
});