Use PHP variable in Ajax

0

By clicking on the positive frame (indicated in the figure by an arrow), the user accepts the friendship invitation.

Ineedtopasstheuserid(value15)totheupdate-friends.phppage.Theeventishostedbytheinvitations.jspage:

$(document).ready(function(){$("#aceitar").click(function(){
     var id = ????????? ;
        $.post('atualizar-amigos.php', {amigo:id}, function(){
            $(".item").remove();
        });
    });
});

The user id is stored in the $ user_id PHP variable. I've tried:

var id = <?= $user_id?>;
var id = <?php echo $user_id; ?>;
var id = "<?php echo $user_id; ?>";

In the first 2 options, it gives an error. In the third, the value passed is

"<?php echo $user_id;?>"

(and not value 15)

I also created the JSON $ frind (printed on the image) and tried:

var id = frind['id'];

But it did not work either. How do I access the id value (in JSON) OR the PHP variable ($ user_id) in the Ajax post function?

    
asked by anonymous 16.07.2017 / 01:13

2 answers

0

You could put an attribute in the input checkbox to store the user id. Then when the checkbox was selected you would get this attribute with the jquery attr function and send it in the ajax request. Here is a small example (with minor modifications to make it as small as possible):

html.php

<!-- Elementos -->
<div>
<!-- Suponha um codigo php arbitrario -->
<?php
//esses dados vem de algum lugar (talvez do banco de dados)
$amigo_id = 25;
?>

    Aceitar <input class="aceitar" type="checkbox" user_id="<?php echo $amigo_id; ?>">

    <div id="resposta">
    A resposta vai aparecer aqui!
    </div>
</div>


<script src="jquery.js"></script>
<script>
    $(document).ready(function(){ 
        $(".aceitar").change(function(){

                if(this.checked){
                var id =  $(this).attr('user_id');
                    $.post('atualizar-amigos.php', {amigo: id}, function(response){
                        //$(".item").remove();
                    $("#resposta").html(response);
                });     
            }
        });
    });
</script>

File update-friends.php

<?php
echo 'amigos atualizados! Apenas um teste. Novo id: ' . $_POST['amigo'];

Of course, updating-friends.php might return a json object in case you need it.

    
16.07.2017 / 18:44
0

Actually they are images and not checkbox, but the solution I made is very similar. In html I did an input hidden:

<input type="hidden" id="campo" value="<?php echo $user_id;?>" />

And in the js file:

var id = document.getElementById("campo").value;
    
17.07.2017 / 21:32