jQuery function .val() does not work - javascript

I'm trying to update the value of the div block
<div id="likeVal">Likes: #Model.Likes</div>
after making an Ajax call as below:
$.ajax({
type: "POST",
async: false,
url: "/Media/VideoLike?likes=" + likes + "&id=" + id
}).done(function(data) {
$("#likeVal").innerHTML = data.likes
});
but the value in the block does not get updated. However when I use document.getElementById("#likeVal").innerHTML = data.likes; the value gets changed. I know that document.getElementById returns a DOM object. I have used the jQuery function in another Ajax call that I made here:
}).done(function(notice) {
if (notice.error || notice.isLastBlock) {
displayStatusMessage(notice.message);
if (notice.isLastBlock) {
$("#assetId").val(notice.assetId);
$("#detailsPanel").show();
}
return;
}
It works fine and the value get's updated in the div block. What am I doing wrong in the first Ajax call?

You are using wrong method for that.
jQuery.val() gets/sets you value of form field. You should use jQuery.html() to get/set content of element.

Related

Dom element is not refreshing in 2nd time but is works in first time

I am doing an ajax call and replacing the response inside a div class. At the first ajax call the response is replaced inside the class properly but 2nd time I got the data from response but the response in not replacing the data inside the class.
I am trying the below way.
$(document).on('click', '#approveallusers', function(){
var checked_ids = []
$("#UserList").find('input[type=checkbox]').each(function () {
var $this = $(this);
if($this.is(":checked") && $this.hasClass('selectbox')){
checked_ids.push($this.attr("userid"));
}
});
$.ajax({
url : '/approve-website-users',
method : 'POST',
data : JSON.stringify({'checked_ids':checked_ids}),
contentType : "application/json",
success : function(data) {
if(data.status == 'success') {
alert(data.res)
$('.users').replaceWith(data.res);
}
}
});
})
here data.res is an html element and its rendering from the server side.
Thanks..
.replaceWith will replace the div including html tags so there won't be any class users.
see this for more info:
http://api.jquery.com/replacewith/#replaceWith-function
maybe you need .innerHTML or .html
check here: http://api.jquery.com/html/#html-htmlString

jQuery not appending title

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);
}
The problem is that the this object in the success function is not the td element. By default the context of the jquery ajax callbacks is set as an object representing the ajax options. However you can change that using the context option:
$('.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()) },
context: this, //make sure "this" inside the success callback is the td element
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')); });
I am assuming that the data returned by Ajax is valid....
the $(this) within success does not refer to the td anymore.
do this outside the ajax call:
var me = $(this);
Then in your success code do this:
me.attr('title', data);
The final console.log statement shows undefined because it occurs before the AJAX request is complete (because AJAX requests are Asynchronous).
Also, a td can't have a title attribute, might need to look at a different option:
how to apply style to 'title' attribute of 'td' tag
And others have stated, can't use $this inside the ajax success function like that.

setInterval() not updating data during multiple calls

I am using following JavaScript code inside a page. The problem is that the code gets executed for the first time and fetches data from from elements.
During the subsequent calls, the changed data in the form elements is not available to this function as it uses data from its maiden call.
$(document).ready(function() {
$('<textarea id="message-clone"></textarea>').insertAfter("#form-message-compose");
var saveDraft = function () {
var originalStriped = $("#wysiwyg").val().replace(/(<([^>]+)>)/ig,"");
if((originalStriped.length) > 10) {
var input = $("<input>").attr("type", "hidden").attr("id", "savedraft")
.attr("name", "submit").val("savedraft");
$.ajax({
type: "POST",
url: $("#form-message-compose").attr("action"),
data: $("#form-message-compose").append(input).serialize(),
success: function(result){
var result = JSON.parse(result);
$("#subject").val(result.message_subject);
$('input[name="draft"]').val(1);
$("#id").val(result.message_id);
var flash = '<div id="flash" class="alert alert-success"><a data-dismiss="alert" class="close">×</a><strong>Yay!</strong> Message Auto saved to drafts!</div>';
$("#page-title").append(flash);
$("#flash").fadeOut(3000, function() { $(this).remove(); });
$("#savedraft").remove();
$("#message-clone").val($("#wysiwyg").val().replace(/(<([^>]+)>)/ig,""));
}
});
}
}
setInterval(saveDraft(), 2000);
});
The problem here is that for the first time, the function fetches correct data from input element #wysiwyg but during the subsequent, it doesnot update the data from the call $('#wysiwyg').val() which results in single execution of the code inside if block.
Kindly guide, where I am doing wrong.
setInterval(saveDraft(), 2000);
should be
setInterval(saveDraft, 2000);
The first argument of setInterval should be a function. You are not passing a function, what you're doing is executing saveDraft and passing the result as an argument.
The issue was with the Tiny MCE I was using. So instead of trying to get the value of texte area by
var originalStriped = $("#wysiwyg").val().replace(/(<([^>]+)>)/ig,"");
I had to use the tinyMCE method to fetch the text
var originalStriped = tinyMCE.get("wysiwyg").getContent({format : "text"});
Another problem with TinyMCE is that it doesnot update the data in textarea on an AJAX call, which otherwise, it does on form submit. So I had to call the trigger the save on tinyMCE manually by calling
tinyMCE.triggerSave();
And then firing the AJAX request with form data.

$(document).Ready() loads Flexigrid, but not when called again by other function outside $(document).Ready()

I have a function called "loadTimeTrackersGrid()", which loads a flexigrid.
The setup looks like this :
$(document).ready(function () {
var editTrackerID = 0;
loadTimeTrackersGrid();
)};
The beginning of the function looks like this :
function loadTimeTrackersGrid(caseStatus) {
var url = 'Utilities/DataViewHandlers/ViewTimeTrackers.ashx?CaseFileID=' + $('#hidCaseFile').val();
if ($('#hidTaskID').val() !== "")
url += '&TaskID=' + $('#hidTaskID').val();
if (caseStatus == "NI") {
url += '&NonInvoiced=1';
}
$('#viewTimeTrackersGrid').flexigrid({
url: url,
dataType: 'json',
method: 'get',
As you can see it calls another page which contains a stored procedure which returns a set of rows and a jsonwriter then puts the returned columns into the flexigrid.
But the problem I am having is outside the (document).ready(), when I have a function that calls the "loadTimeTrackersGrid()", it never reloads the flexigrid or makes a call to the file that contains the stored procedure.
My function(that I am trying to get to work) looks like this :
function returnInvoicedItems() {
loadTimeTrackersGrid();
$('.menuBtn img').parent().children('ul').removeClass('menuShow');
}
And this is how I am calling "returnInvoicedItems" function:
<li>Non Invoiced Tracker</li>
I am not sure, but I think I can see the problem. Your second function returnInvoicedItems() that calls loadTimeTrackersGrid(), it does have a jQuery code (in the line $('.menuBtn img').parent().children('ul').removeClass('menuShow');. Now, if you have a jQuery call, don't you have to do make that call inside $(document).ready()?
Try to move returnInvoicedItems() inside $(document).ready() and see what happens.
This works like a gem:
$('#viewTimeTrackersGrid').flexOptions({ url: 'Utilities/DataViewHandlers/ViewTimeTrackers.ashx?' + invoicedUrl + '&NonInvoiced=1' }).flexReload();

jquery $(this) object missing issue

I have a problem with jQuery's $(this) object and make me miss the this element
in code :
$('.star').click(function (){
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() + 1;
var ThisStar = $(this);
alert(ThisStar.parent().html())
$.ajax({
type: 'POST',
url: EXECUTION_URL + 'ajax/rate.php',
data: {'article' :id ,'rate': vote},
success:function(data,tt,ff){
alert(ThisStar.parent().html())
}
});
the first alert fire : the true contents of the parents of the clicked node
the second alert fire : null !!!!
why it have been changed into the ajax ? or from another reason ? please tell me a good solution for this issue
ok actually i checked my code that there is two lines after the ajax function that delete the stored node in the this object and because of the ajax function is asynchronous function the two lines executed before the code inside the success function >> thanks for all
Your code should work fine, check the proof. The only difference would be this:
success:function(data,tt,ff){
alert(ThisStar.parent().html())
}
vs.
success:function(data,tt,ff){
alert(ThisStar.parent().html())
}});

Categories