setInterval() not updating data during multiple calls - javascript

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.

Related

jQuery function .val() does not work

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.

Independent jquery functions execute consecutively when one is called

My problems seems basic, yet I have tried a lot of different ways of putting these functions on one html file to no avail. The problem is that, when the 1st function is called, the second also runs, leaving me with the results of the second function all the time. I have no idea what I am doing wrong, please help. Here is the code in question.
<script>
$(document).ready(function () { // Make sure the elements are loaded on the page
// Listen for a click event on the button
$('#buttonON').click(funct);
$('#buttonOFF').click(funct2);
});
// Now define the function
function favfunct(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "1", "caroff" : "0"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
function funct2(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "0", "caroff" : "1"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
}
</script>
You have omitted the closing brace from the function favfunct().
Please use this,
<script>
$(document).ready(function () {
function funOne(){
};
function funTwo(){
};
$('#buttonON').live('click',function(){
funOne();
});
$('#buttonOFF').live('click',function(){
funTwo();
});
});
NOte: initialize function before use and initialize them into document ready.

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.

Jquery each() function loop with Ajax

I wish to replace values in each div class with my ajax result but i cannot seem to append my table result to the individual div class during the loop. I know somehow the $(this).append(table) is placed wrongly because it is not outside of the ajax request. How can i modify this to get the effect i wanted?
my script is as such:
$('.developer_badgesarea').each(function(){
// get the div class value to perform ajax
var player_id = $(this).html();
var table;
// if condition to conduct ajax
if(player_id != 'None'){
$.ajax({
// ajax stuff here
success: function(result){
//table created here
$(this).append(table);
}
});
}
});
Issue is your "this" reference inside the ajax success function. It references the callback function, instead of the dom element you are intending it to be referenced.
$('.developer_badgesarea').each(function(){
// element reference to your div, that you'll access inside your ajax call
var elm = $(this);
// get the div class value to perform ajax
var player_id = elm.html();
var table;
// if condition to conduct ajax
if(player_id != 'None'){
$.ajax({
// ajax stuff here
success: function(result){
//table created here
elm.append(table);
}
});
}
});

Remove html elements added dynamically with JQuery

In my html page, I have a select with some options.
When selecting an option, an ajax call is fired passing the option's value to a php script, which returns an html fragment (another select) with a certain id that is appended to the page.
When the user selects another option from the first select, the event is fired again, the ajax call is executed and another html fragment (with the same id) gets appended to the page.
I want that, if the event is fired a second time, the appended element is removed form the page before appending the new one.
At the moment I'm using this code:
$(document).ready(function() {
$("#id_serie").change(function() { //#id_serie is the if of the first select
if ($("#id_subserie_label")) { //#id_subserie_label is the id of the html element returned by the ajax call
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
This is not working though, the html element returned by the second ajax call is appended after the element returned from the first call (because the element with id #id_subserie_label is not in the page when the script is loaded?).
How can I achieve what I need?
You're very close.
Just change if ($("#id_subserie_label")) to if ($("#id_subserie_label").length):
$(document).ready(function() {
$("#id_serie").change(function() {
if ($("#id_subserie_label").length) { // <=== change this line
console.log("Removing");
$("#id_subserie_label").empty().remove();
}
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});
See The jQuery FAQ: How do I test whether an element exists?.
This is because, as Ivo points out:
$("#id_subserie_label") is an object, and objects always evaluate to true.
As per Andy E's comment, you can simplify your code to this, if you don't need the console.log() call:
$(document).ready(function() {
$("#id_serie").change(function() {
$("#id_subserie_label").empty().remove();
var url = 'myscript.php';
var id_s = $(this).val();
$.post(url, {id_serie: id_s}, function(data) {
$("#id_serie").parent().after(data);
});
});
});

Categories