Take Variable JS and take it to PHP WITHOUT JQUERY

0

* I want to put together an experience system for a game. The idea itself is that within this function:

 function Experiencia(...parámetros para definir la exp final){
    return expC = 50;  
}

... a process is armed depending on what was fought, how much experience is returned.

* Now to be able to update the experience that the player already had, I need to obtain that variable value and send it via AJAX to a file "ActualizaStat.php" so that I can make an UPDATE in the MYSQL database.

<button id="btnInfComb"> <a href="enviaDatosCombate.php">Aceptar</a></button>

function EnviaDatosCombate() {

    var xhr = new XMLHttpRequest()
    xhr.open("POST","ActualizaStat.php",true)
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4 && xhr.status == 200){
           var a = Experiencia()
           //Aca dentro que tendria que hacer para poder mandar el valor en 
           //SEND
        }
    }

    xhr.send(a)
}

* On the PHP side of "ActualizaStat.php" I would have the following piece of code. (It is not necessary to tell me how to perform the update, I only show this fragment to know that I call it through POST ..)

<?php
$datos = $_POST['a'];
echo $datos;
?>

I would greatly appreciate the help as always.

    
asked by Alfacoy 11.12.2017 в 21:50
source

1 answer

1

The event xhr.onreadystatechange is executed once the whole process of sending and returning data has finished, so there you would not send any data to your php.

In your JS you could send the data in this way:

<button id="btnInfComb" onclick="EnviaDatosCombate()">Acepta</button>

function Experiencia(){
    return expC = 50;  
}

function EnviaDatosCombate() {

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "ActualizaStat.php", true);
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4 && xhr.status == 200){
           //Aca recibes los datos de vuelta en caso de que existan
        }
    }

    var exp = Experiencia();

    var datos = new FormData();
    datos.append('experiencia', exp);

    xhr.send(datos)
}

And in your PHP you receive them like this:

<?php
    $datos = $_POST['experiencia'];
    echo $datos;
?>
    
answered by 11.12.2017 / 22:01
source