0

I have used this script to set an order.

<script type="text/javascript">
$( "#post_list" ).sortable({
    placeholder : "ui-state-highlight",
    update  : function(event, ui)
    {
        var post_order_ids = new Array();
        $('#post_list li').each(function(){
            post_order_ids.push($(this).data("post-id"));
        });
        $.ajax({
            url:"ajax_upload.php",
            method:"POST",
            data:{post_order_ids:post_order_ids ,var_i_want:<?php print $var_i_used;?>},
            success:function(data)
            {
             if(data){
                $(".alert-danger").hide();
                $(".alert-success ").show();
             }else{
                $(".alert-success").hide();
                $(".alert-danger").show();
             }
            }
        });
    }
});
</script>   

Now i would like to add a $var (set in php) to be send with it to ajax_upload.php I am not familiar with javascript. Is this possible?

EDIT: Got it line is updated how it works. Thnx.

  • Does this answer your question? [How do I pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript) – MC Emperor Sep 10 '20 at 10:17
  • Got it, had to edit the line: data:{post_order_ids:post_order_ids}, --> data:{post_order_ids:post_order_ids ,var_i_want:}, – Dries Benders Sep 10 '20 at 10:25
  • Please also make sure, that the content is not user controlled (Like $_POST[XXX]) or sanitize the code to prevent XSS attacks. – Bellian Sep 10 '20 at 10:26

3 Answers3

0

You need to specify where you want to add this variable exactly, otherwise you can pre-render js variable from server side using php like this :

your other code <?php echo "var var_name = var_value;"; ?> your other code

Faical ARAB
  • 387
  • 3
  • 14
0

Before $.ajax({, you should get the php value. e.g. var variable_name = '<?php echo $var?>';

after that you can set the variable in data: data:{post_order_ids:post_order_ids,var:variable_name},

0

Here is one way to do that:

$.ajax({
    url:"ajax_upload.php",
    method:"POST",
    data:{
            post_order_ids:post_order_ids,
            myVarFromPhp: <?php echo (($var) ? $var : "null"); ?>
         },
    ...
Ahmad
  • 12,336
  • 6
  • 48
  • 88