To pass the variable from JavaScript
to php
I do it with Ajax
in this way:
<script type="text/javascript">
function ejecutar(num_js){
$.ajax({
url: 'mi_php.php',
type:'POST',
data: {num:num_js},
success : function(json){
$('#contenedor-texto').html(json);
console.log("success");
console.log(json);
alert(json);
}
});
}
</script>
And so I get the value of the variable in php
:
<?php
$num = $_POST["num"];
?>
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(num_js){
$.ajax({
url: 'mi_php.php',
type:'POST',
data: {num:num_js},
success : function(json){
$('#contenedor-texto').html(json);
console.log("success");
console.log(json);
alert(json);
}
});
}
</script>
</head>
<body>
<button type="button" onclick="ejecutar('12');">Ejecutar</button>
</body>
</html>
This is my full mi_php.php
file:
<?php
$num = $_POST["num"];
echo "Num = ".$num." ";
$link = mysql_connect('localhost', 'root', 'passw');
if (!$link){
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * from tabla where num = '".$num."' ";
echo "Consulta SQL = ".$sql;
$result_q = mysql_query($sql);
$array_return = array();
while($result = mysql_fetch_array($result_q)){
$array_return[$result['campo']]['campo1'] = $result['campo1'];
$array_return[$result['campo']]['campo2'] = $result['campo2'];
$array_return[$result['campo']]['campo3'] = $result['campo3'];
$array_return[$result['campo']]['campo4'] = $result['campo4'];
}
?>
The console.log(json);
and the alert(json);
of the file index.php
show me the following:
Num = 12 Consulta SQL = SELECT * from tabla where num = '12'
But the echo "Consulta SQL = ".$sql;
of line 10 of the file mi_php.php
shows me the following:
Consulta SQL = SELECT * from tabla where num = ''
And the result of the query SQL
on the web page is as if it had done this:
SELECT * from tabla where num = ''