Use PHP variable in Ajax

Asked

Viewed 557 times

0

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

inserir a descrição da imagem aqui

I need to pass the user id (value 15) to the update-friends.php page. The event is held by the invitations.js page :

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

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

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

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

"<?php echo $user_id;?>"

(and not the 15)

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

var id = frind['id'];

But tbm didn’t work. How I access the id value (in JSON) OR PHP variable ($user_id) in the Ajax post function?

  • 1

    has already answered the question itself.. var id = "<?php echo $user_id; ?>";

  • Did you run these tests directly in the PHP file that contains HTML or in a JS file? Because it seems that PHP was not interpreted in the file, which indicates that the code is not in a PHP file.

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 take this attribute with the jquery attr function and send it to the ajax request. Take this small example (with small 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 may return a json object if you need it.

0

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

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

And in the js file:

var id = document.getElementById("campo").value;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.