1
Good morning friends, I have these buttons here:
<button class="btn-excluir" data-id="1">Primeiro</button>
<button class="btn-excluir" data-id="2">Segundo</button>
<button class="btn-excluir" data-id="3">Terceiro</button>
<button class="btn-excluir" data-id="4">Quarto</button>
<button class="btn-excluir" data-id="5">Quinto</button>
And this simple script:
<script type='text/javascript'>
var btn = document.getElementsByClassName('btn-excluir');
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function (e) {
var a = e.target.dataset.id;
ajax_envio('script.php?variavel=' + a);
}, false);
}
function ajax_envio(arquivo) {
var http = new XMLHttpRequest;
http.open('GET', arquivo, true);
http.send();
}
</script>
The PHP code, to get the variable value:
<?php $valor_da_variavel = $_GET['variavel'];
echo "Valor da variável: $valor_da_variavel"; ?>
The script basically takes the data-id of the button and sends this value to the variable $value_da_variable.
But here’s the problem: the URL doesn’t want to change, although when I squeeze F12 and I go to the part NETWORK, and I click one on some button, shows, in the column Name, what should look like in URL. It appears basically this:
Name: script.php? variable=2 (if I click the second button)
Status: 200 OK
Type: xhr
Initiator: script.php:72 (on the line where the http send.();)
Size: 2.5kb
Team: 10ms
And since I am using $value_da_variable as parameter in a function, it is returning null.
I wonder what the problem might be. As for PHP. the error message I have is:
Index undefined: value_da_variable (Which is the $value_da_variable);
Thank you in advance!!
And this
:
after theecho
?– Sam
Oops, when editing here I must have put, but in my code is normal, without the ":"
– A. Silva
Then the problem should be in the PHP function. Ajax is sending the value normally.
– Sam