On my page I want the user to be able to mouseover
a td
element, have the page make an Ajax call to the server, and then append a title
attribute to the td
to serve as a tooltip for the remainder of the time the user is on the page.
The information the page needs to retrieve is very basic so there's nothing too complicated about this... however I cannot get the code to append the data
I receive from the Ajax call onto the td
element.
Jquery/Ajax
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '@Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title'));
});
Unfortunately I can see, in the console, the 'ajax'
entry, followed by the exact value I'm expecting for the data
object, but undefined
appears as the value for the td
title
attribute from the final console.log
statement (end of the mouseover
).
HTML/Razor
<td class="ChannelCodeDesc">
@Html.DisplayFor(model => model.displayForPaging[i].ChannelCode)
@Html.HiddenFor(model => model.displayForPaging[i].ChannelCode)
</td>
Ajax Controller Method
public JsonResult GetDesc(string channel)
{
var description = (from c in db.Channel
where c.ChannelCode.Equals(channel)
select c.ChannelLongDescription).FirstOrDefault();
return Json(description, JsonRequestBehavior.AllowGet);
}