将特定PHP变量发送回jQuery的正确方法?

I'm kinda confused how to solve this problem in a right way..

This is jQuery function I intend to use. Runs on 1.7.2 jQuery, PHP 5.2.

    $(function() {
        var timer = setInterval( showDiv, 5000);

//var categoryid = ;??

        function showDiv()
        {

        $.post("check4_new_data.php?categoryid="+encodeURIComponent(categoryid),
        function(response)
        {
            $('#awaiting').fadeOut(400); //cosmetics, nothing important
            $('#posting1').html(unescape(response));
            $('#posting1').fadeIn(200);
        });

       }
    });

Question:

There is a PHP variable $categoryid set when PHP page loads and.. this function needs it. So, how to send $categoryid back to jQuery in a right, safest way?

Note:Ive been using cookie as first test to keep categoryid present for PHP, but then all opened (and different) pages started to load up same data (according to latest page visited).

Thx!

You could do it like this:

<div id="posting1" data-category="my_category">
    ...
</div>

This way, your markup and JavaScript can be separated completely. So you can fetch the category for the related post you are trying to refresh:

var category = $('#posting1').attr('data-category');
$.post(
    "check4_new_data.php?categoryid="+encodeURIComponent(category), 
    function (response) {
        $("#posting1").html(response);
    }
);

Use json_encode;

var categoryid = <?php echo json_encode($categoryid);?>;

json_encode always produces a JavaScript-safe encoding. Even for complex variables and multidimensional arrays, and it's type-safe (for scalars at least).

You may try this.

json_encode;

  var categoryid = <?php echo json_encode($categoryid);?>;

For further details: http://php.net/manual/en/function.json-encode.php