HelpNeeder HelpNeeder - 10 days ago 5
Ajax Question

Passing objects between timers and post ajax requests (anonymous functions)

I have struggled on this topic for a quite a bit of time and it just won't click!

I need to pass the object to the

&.post
(WordPress processed AJAX) request, but I cannot figure out how to do it correctly using regular variables; instead, I'm forced to call $(document) and iterate over it's DOM elements (very ugly and slow).

How would I correct this code so I'm able to pass the title variable all the way to the post data, instead using
$(document).find('#sections_title').val() request
?

Please explain how to do this properly.

(function ($) {
var title = $('#sections_title');
var timeout = 2000;

var delay = (function () {
var timer = 0;

return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();

title.keyup(function () {

// i would like to have variable here, that grabs the $(this).val()
// and use this variable to pass to the data
// var value = .......

delay(function () {
$.post(
ajaxurl,
{
'action': 'add_foobar',
'data': $(document).find('#sections_title').val()
// instead I would like:
// 'data': value
},
function(response){
alert('The server responded: ' + response);
}
);

}, timeout);
})();
})(jQuery);

Answer

This should be easiest way for your case. Bind the val as object to callback. Then cast this to string when you need to use it.

    delay(function () {
        $.post(
            ajaxurl,
            {
                'action': 'add_foobar',
                'data': String(this)
                // instead I would like:
                // 'data': value
            },
            function(response){
                alert('The server responded: ' + response);
            }
        );

    }.bind(Object($(this).val())), timeout);

Or here is the complete code

(function ($) {
    var title = $('#sections_title');
    var timeout = 2000;

    var delay = (function () {
        var timer = 0;

        return function (callback, ms) {
            clearTimeout(timer);
            timer = setTimeout(callback, ms);
        };
    })();

    title.keyup(function () {

        // i would like to have variable here, that grabs the $(this).val()
        // and use this variable to pass to the data
        // var value = .......

        delay(function () {
            $.post(
                ajaxurl,
                {
                    'action': 'add_foobar',
                    'data': String(this)
                    // instead I would like:
                    // 'data': value
                },
                function(response){
                    alert('The server responded: ' + response);
                }
            );

        }.bind(Object($(this).val())), timeout);
    })();
})(jQuery);