Error when passing variable from Javascript to PHP from the same file?

0

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

    
asked by El Cóndor 12.07.2017 в 05:14
source

1 answer

1

Specific errors can be seen at first glance, such as:

  • Try to print variables without being declared or assigned with any value (PHP) specifically variable $identificador for which it will show an undefined variable error.
  • I do not understand with what end you try to print the variable num since you are using it as the clave of the value of the variable count that you access from PHP .
  • The error it shows in the console is precisely because of this, it is not declared at the function level to be able to access, it will only be accessible for ajax . So the first solution would be to declare it before and initialize it but it would not make sense since it does not use anything except for the key of the value sent.
  • As you are making the call ajax to same file PHP will return the content HTML also, preferably create another file for only data processing from PHP and change in url in ajax for example test.php where you would go only your code PHP or cut with exit finish the execution and place the code at the beginning of html , I recommend the first option, create a new file

Your code would be:

 <?php
  /* Para validar que la solicitud sea de tipo POST , (solo para ajax se ejecutará)*/
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if(isset($_POST['num'])){
        echo "num = ".$_POST['num'];
        exit(); /* Para que no siga imprimiendo el resto*/
    } else{
        echo "variable vacia";
        exit();
      }
   }
  ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Ajax con php</title>
    <meta charset="utf-8">
    <script src="js/jquery-2.1.1.min.js"></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");
                    console.log(json);
                },


            });

        }
    </script>
</head>

<body>

    <button type="button" onclick="ejecutar();">Ejecutar</button>
</body>
</html>
    
answered by 12.07.2017 / 06:06
source