First of all mention that I found similar questions to this with possible solutions or closed because they are duplicated but without a solution.
To pass the variable from JavaScript
to php
I decided to do it with Ajax
in this way:
<script type="text/javascript">
function ejecutar(){
console.log("Inicia");
var count = 5;
$.ajax({
url: "index.php",
type: "POST",
data: {num:count},
success : function(json) {
console.log("success");
},
error : function(xhr, status) {
console.log("error "+" xhr: "+xhr+" Status: "+status);
},
complete : function(xhr, status) {
console.log("complete "+" xhr: "+xhr+" Status: "+status);
console.log("count = "+count);
console.log("num = "+num);
}
});
console.log("Fin");
}
</script>
And so I want to get the value of the variable in php
:
<?php
if(isset($_POST['num'])){
echo "num = ".$identificador;
}else{
echo "variable vacia";
}
?>
This is my full index.php
file:
<!DOCTYPE html>
<html>
<head>
<title>Ajax con php</title>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.min"></script>
<script type="text/javascript">
function ejecutar(){
console.log("Inicia");
var count = 5;
$.ajax({
url: "index.php",
type: "POST",
data: {num:count},
success : function(json) {
console.log("success");
},
error : function(xhr, status) {
console.log("error "+" xhr: "+xhr+" Status: "+status);
},
complete : function(xhr, status) {
console.log("complete "+" xhr: "+xhr+" Status: "+status);
console.log("count = "+count);
console.log("num = "+num);
}
});
console.log("Fin");
}
</script>
</head>
<body>
<?php
if(isset($_POST['num'])){
echo "num = ".$identificador;
}else{
echo "variable vacia";
}
?>
<button type="button" onclick="ejecutar();">Ejecutar</button>
</body>
</html>
The result I get in the Google Chrome Developer Tools console is as follows:
and in the browser the following:
Finally mention that it is the 1st time I do this so if I am omitting something basic or simple an apology