First of all mention that I found questions similar to this one with possible solutions or closed for being duplicates but without a solution.
To pass the variable from JavaScript
to php
I decided to do it Ajax
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 complete file index.php
:
<!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 the following:
and in the browser the following:
Finally mention that it is the 1st time that I do this so if I am omitting something basic or simple an apology
Specific errors can be seen at first sight, such as:
$identificador
for which it will show an undefined variable error.num
since you are using it as theclave
value of the variablecount
you access fromPHP
.ajax
. Therefore, the first solution would be to declare it before and initialize it, but it would not make sense since it does not use it for anything except for the key of the sent value.ajax
to the same file , it willPHP
return the contentHTML
as well, preferably create another file for only the data processing fromPHP
and it would change in theurl
inajax
for exampletest.php
where only your code would goPHP
or cut withexit
finish the execution and place the code at the beginning of thehtml
, I recommend the first option , create a new fileYour code would be: