Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top