Error passing variable from JavaScript to PHP

1

I'm trying to pass a variable from JavaScript to PHP, but I get an error that I do not understand why.

The code I have is the following:

<script>
var dias = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
 var mes = '<?php echo $mes;?>';
 var dia = '<?php echo $dia;?>';
 var ano = '<?php echo $any;?>';
var fec = mes+"/"+dia+"/"+ano;
      var day = new Date(fec).getDay();
     <!---document.write(dias[day]);

     $.ajax({
    var a = document.write(dias[day]);
    url:"includes/apen_files/recarga_agenda_pordias.php",
    data:{envio:a},
    type:"post",
    success:function(a){
        document.getElementById("demo").value = a;
    }
});

</script>

What is the part of the script without PHP does work, but reading online tutorials have given me the option to pass it from JS to PHP that way. But when I execute it I get the following error:

  

Parse error: syntax error, Undefined index: send on line 38

Which is the line of the PHP file that loads the POST value:

$ variable = $ _POST ['send'];

I do not know if I'm doing it right or there is some simple error, in that case I apologize.

    
asked by Joume Parra 18.06.2018 в 17:29
source

4 answers

1

I do not know exactly what you want to do with this use of Javascript, since Javascript is normally used to update data in a form or so. In any case, the error it gives you is because your quotation marks are not right, you should use simple or double quotes that you use with shift + 2 (the same thing happens in the following line in PHP, apart from forget to use the $ for the variable). On the other hand, you must end the Javascript instruction with ";" So the code would stay like this on line 52:

<?php $DiaSemanaW = "<script> document.write(diasemanavar) </script>"; ?> <?php echo "DiaSemanaW = ".$DiaSemanaW; ?>

Obviously, nothing will appear in the result because PHP always loads before JavaScript (remember that PHP is a server language).

    
answered by 18.06.2018 в 17:50
1

Your code has a lot of errors that I will enumerate starting with this block:

$.ajax({
  var a = document.write(dias[day]);
  url:"includes/apen_files/recarga_agenda_pordias.php",
  data:{envio:a},
  type:"post",
  success:function(a){
      document.getElementById("demo").value = a;
  }
});

The parameter passed to .ajax() is a class that is defined between keys { datos } that could erroneously induce you to be similar to the definition of a function, so that the value assignment you make ( var a = document.write(dias[day]); ) It is incorrect and will give you an error.

Also, you are assigning the variable a what returns document.write and not the day of the week obtained.

To continue, success from jQuery 3.0 is called done :

  

Deprecation Notice: The jqXHR.success() , jqXHR.error() , and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done() , jqXHR.fail() , and jqXHR.always() instead.

In Spanish:

  

Obsolescence notice: The jqXHR.success() , jqXHR.error() and jqXHR.complete() methods have been removed in jQuery 3.0. You can use jqXHR.done() , jqXHR.fail() and jqXHR.always() instead.

It can be used as a method, so your code would be:

var a = dias[day];
$.ajax({
  url: "includes/apen_files/recarga_agenda_pordias.php",
  data: {envio:a},
  type: "post",
}).done(function(a) {
  document.getElementById("demo").value = a;
});

On the other hand, I have to tell you that the only sure way to send PHP data to javascript is by using json_encode() and never by printing the content of a variable directly:

var mes = <?= json_encode($mes) ?>;
var dia = <?= json_encode($dia) ?>;
var ano = <?= json_encode($any) ?>;

It is not necessary to put the values in quotes because json_encode() will put quotation marks if the content is a string of characters. In case of Boolean or numeric values it will not put them (they are not necessary).

Finally, it is not recommended to call the Date() constructor with a localized date string. It is advisable to use the constructor in which the day, month and year are used as parameters:

var day = new Date(
  <?= json_encode($any) ?>,
  <?= json_encode($mes) ?>,
  <?= json_encode($dia) ?>
).getDay();

This is the code that I used to reproduce your problem and fix it:

nuevo.php

<?php
/* El 28 de febrero de 2018 fue miércoles */
$mes = 02;
$dia = 28;
$any = 2018
?><!DOCTYPE html>
<html lang="es">

<head>
    <title>Título de ejemplo</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>

<body>
    <script>
    var dias = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
    var day = new Date(
        <?= json_encode($any) ?>,
        <?= json_encode($mes) ?>,
        <?= json_encode($dia) ?>
    ).getDay();
    console.log('Enviando el valor', dias[day]);
    $.ajax({
        url: 'receptor.php',
        data: {
            envio: dias[day],
        },
        type: 'post',
        dataType: 'json',
    }).done(function(a) {
        console.log(a);
        document.getElementById("demo").value = a;
    });
    </script>
    <input type="text" id="demo" value="Valor inicial" size="40" />
</body>

</html>

receptor.php

<?php
/* Indicamos que el valor devuelto será JSON codificado en UTF-8 */
header('Content-type:application/json; charset=utf-8');
/* Obtenemos el valor enviado por XHR */
if (isset($_POST['envio'])) {
  $variable = $_POST['envio'];
} else {
  $variable = '(no se recibieron datos por POST)';
}
/* Devolvemos una cadena montada con dicho valor */
echo json_encode("Hemos recibido: $variable");
    
answered by 19.06.2018 в 08:48
0

Well, I know that to interact javascript or jquery with php is done through ajax and send it either by POST or GET method.

  $.ajax({
        var a = "Tu valor";
        url:"includes/controler.php",
        data:{eliminarContact:a},
        type:"post",
        success:function(a){
            location.reload();
        }
    });
    
answered by 18.06.2018 в 18:03
0

What you have to do is send your data to your php code.

$.ajax({
    var a = document.write(dias[day]);
    url:"includes/apen_files/recarga_agenda_pordias.php",
    data:{envio:a},
    type:"post",
    success:function(a){
        location.reload();
    }
});

Then in your php file you do the function you want to do.

if(isset($_POST['envio'])){
//Aqui obtienes la variable $_POST[envio] y haces las funciones que vayas a hacer luego la imprimes
echo $variable;
}

and in the last part of the ajax you assign it to your element through the ID or class or by selector.

success:function(a){
        document.getElementById(“myselector”).value = a;
    }
    
answered by 18.06.2018 в 18:48