pass value of php variables to javascript of different file

1

I have a php code (test.php) in which I have a couple of variables ($ lati and $ longi) whose values I want to send to a .js (main.js) to use them in variables javascritp but I have not got it , after some attempts I decided to clean the main.js code to request their help, I hope you can help me.

test.php

<?php

header('Location: test.php?$longi='.$longi.'&lati='.$lati);

$coordenada = $_GET['valor'];

//Substraemos los grados y minutos de latitud
$latgrados = substr($coordenada, 18, 2);
$latminnmea = substr($coordenada, 20, 8);

//Divide los minutos entre 60
$latmnin = ($latminnmea/60);

$latitud = $latgrados+$latmnin;


$lati = substr($latitud, 0, 9);



//Substraemos los grados y minutos de longitud
$longrad  = substr($coordenada, 31, 3);
$lonminnmea = substr($coordenada, 34, 8);

//Divide los minutos entre 60
$longmin = ($lonminnmea/60);

// MUltiplica los grados por -1 para que salga negativo
$long = ($longrad);

$longitud = $long+$longmin;

$longi = substr($longitud, 0, 10);

$longi= $longi*-1;

echo $lati.", ".$longi;



$link = mysqli_connect("localhost","admin","m3dina","motor");
mysqli_select_db($link, "motor");
$tildes = $link->query("SET NAMES 'utf8'"); //Para que se muestren las 
tildes
$result = mysqli_query($link, "INSERT INTO tbl_coordenadas(FECHA,COORDENADA) 
values ('2017/11/10','".$coordenada."')");


?>

main.js

(document).ready(function($) {



    /*Google map canvas*/
    jQuery(document).ready(function initialize() {
        var mapOptions = {

          center: new google.maps.LatLng(lati, longi),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };



        var map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);

        var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(lati, longi),
                        map: map,
                        title: 'Aid',
                        icon: 'img/icon.png'
        });


    });





    /////////////////////////////
    // FORMA DE CONTACTO////////
    ////////////////////////////

    $("#contacto-form").validate({
        rules: {
            msg: {
                minlength: 20
            }
        },
        submitHandler: function(){
            //Variables de los campos
            var nombre = $('#nombre').val();
            var email = $('#email').val();
            var telefono = $('#telefono').val();
            var comentario = $('#comentario').val();
            //var comentarios = $('#comentarios-contacto').val();
            $.ajax({
                beforeSend: function() {
                   /* $('#loadingFormContacto').show();
                    $('#buttonEnviarContacto').hide();*/
                },
                type: "post",
                url:'process.php',
                data:{
                    // Datos a enviar
                    nombre:nombre,
                    email:email,
                    telefono:telefono,
                    comentario:comentario
                    //comentarios:comentarios
                },
                success:function(){
                    $('#contacto-form')[0].reset();
                   /* $('#loadingFormContacto').hide();*/
                    $('#buttonEnviarContacto').show();
                    //alert('¡Mensaje enviado con éxito! Muchas gracias.');
                    $('#mensaje-enviado').show('slow');
                    // Luego lo ocultamos después de un tiempo.
                      setTimeout(function(){
                          $('#mensaje-enviado').hide('slow');
                      }, 5000);
                },
                error:function(){
                    alert('Hubo algún error en el envío del formulario.');
                    $('#loadingFormContacto').hide();
                    $('#buttonEnviarContacto').show();
                }
            });
        }
    });

    $.extend($.validator.messages, {
        required: "Favor de completar este campo.",
        email: "Favor de completar con un email válido",

    });;


});
    
asked by lalo 22.11.2017 в 14:25
source

2 answers

1

to do this data transfer, I think the way would be to embed the javascript code in the php file, since the data flow is usually from javascript to php not the other way around.

    <?php

<script>
    jQuery(document).ready(function initialize() {
            var lati =  "<?php echo $lati ?>";
            var longi = "<?php echo $longi ?>" ;
            var mapOptions = {

              center: new google.maps.LatLng(lati, longi),
              zoom: 16,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };



            var map = new google.maps.Map(document.getElementById("map_canvas"),
                mapOptions);

            var marker = new google.maps.Marker({
                            position: new google.maps.LatLng(lati, longi),
                            map: map,
                            title: 'Aid',
                            icon: 'img/icon.png'
            });


        });
       </script>
    ?>

Greetings.

    
answered by 22.11.2017 в 15:23
0

The correct way to return information to a view is with a return. Do not do what you advise above it is very bad practice to combine HTML with PHP. What you need is to use Ajax. You can use the axios library. It is very simple and clean. An example.

axios.pots (URL, {parameters}). then (res = > {

Consolé.log (res.data);

}, error = > {

Consolé.log (error);

});

In your PHP file

$ data = (object) Array (

'data1' = > $ var1,

'data2' = > $ var2,

);

return json_encode ($ data);

    
answered by 06.09.2018 в 13:40