R
First of all, it is appreciated that you have shown all the code that you have tried so far, it is seen that you have worked a lot on this, but as a recommendation, when you see that you are stuck, come quickly with the code you have at that time and the problems you have presented, do not wait five months to do so, this will prevent your code from growing and accumulate more and more mistakes I will try to go for points by telling you where there are errors in your code at the same time I will give you advice and good practices:1 - Today you do not need to detect browser capabilities to know if you build an object https://developer.mozilla.org/es/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest or ActiveXObject. If you don't need to support smaller Internet Explorer versions than version 8 (and https://www.microsoft.com/en-us/microsoft-365/windows/end-of-ie-support ), you can use without any problem XMLHttpRequest. In the examples I will show you I will assume that you are working minimally with Internet Explorer 10.2 - You must not include a file PHP like a file JavaScript That's it. The code PHP is to run it on the server, so you don't need to refer to it. The following line:<script src="funcionesPHP.php"></script>
You should remove her.3 - If your functions make numerical calculations, it is best for you to declare numerical variables instead of strings, this will prevent you from having to be making unnecessary conversions over and over.4 - https://es.stackoverflow.com/questions/192300/en-qu%C3%A9-momento-se-vuelve-necesario-usar-la-funci%C3%B3n-eval-de-javascript . In your case, you're using it only to convert chain-to-numeric variables, but if you follow my previous recommendation or use the operator +, https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/parseInt Or do a cast to Number you don't need to use it:var variable = "100";
console.log(typeof +variable);
console.log(typeof parseInt(variable));
console.log(typeof Number(variable));5 - The return you do inside onreadystatechange It doesn't have the effect you expect. You think it's the return of the function. DamePotenciaViaPHP, but in reality this last one has no return, so it will always return undefined. Note the following snippet:// Esta función no tiene un retorno por lo que siempre
// devolverá undefined
function prueba (numero) {
setTimeout(function() {
// Este retorno afecta a la función enviada
// al setTimeout, no afecta a la función prueba
return numero++;
}, 100);
}
console.log( prueba(2) );6 - On the other hand, you must keep in mind, that when you make a call AJAX, the server response is asynchronous, so it will not be immediately available. You should not try to match the function response to a variable that way, because as I told you earlier the function you are using returns undefined. Note the following snippet to understand that the value returned by PHP You get it after the moment you're trying to get its value:function getTodos() {
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
request.onload = function() {
if (this.status === 200) {
console.log("Este console.log se ejecutará más tarde, en este momento es realmente cuando se obtiene el valor que estás intentando guardar en la variable PotenciaPHP");
}
};
request.send();
}
getTodos();
console.log("este console.log se ejecutará primero, en este momento estás intentando asignar un valor a PotenciaPHP pero el mismo no está disponible");Therefore, this code will not do what you are looking for:PotenciaPHP = DamePotenciaViaPHP(Base, Exponente);
alert("Potencia PHP: " + Base + " ^ " + Exponente + " = " + PotenciaPHP);
Since the value the server will return will not be available at the time you are trying to access it. To do what you're looking for, you should use or callback or https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise to run the code you need to access the data once they are returned.7 - Another problem you have is that you are trying to access PHP to variables sent by POST:$base = $_POST["base"];
$exponente = $_POST["exponente"];
However in the code JavaScript Make a request GET:xmlhttp.open("GET", "funcionesPHP.php", true);
8 - I don't know you're trying the following line:xmlhttp.send("PHPDamePotencia?base=" + base+"&exponente=" + exponente);
But just send the variables base and exponente the server, the first part concerning PHPDamePotencia I'd have to stay like this.xmlhttp.send("base=" + base+"&exponente=" + exponente);
9 - And finally, you are writing the result returned by the server in a supposed element I don't see in your code HTMLdocument.getElementById("myText").innerHTML = this.responseText;
return document.getElementById("myText").innerHTML;
If the element with id myText does not exist, the previous code should throw you a mistake as getElementById I null.With all this in mind, here I leave you a variation of your code that should work for you. Note as the third parameter of the function DamePotenciaViaPHP It's a function. callback:function DamePotenciaViaPHP(base, exponente, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "funcionesPHP.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onload = function() {
// Una vez recibida la respuesta del servidor
callback(
xmlhttp.status === 200
? +xmlhttp.responseText
: 'MAL'
);
};
xmlhttp.send("base=" + base + "&exponente=" + exponente);
}
And to call the function, you do it the following way:DamePotenciaViaPHP(Base, Exponente, function (PotenciaPHP) {
alert("Potencia PHP: " + Base + " ^ " + Exponente + " = " + PotenciaPHP);
});