Convert javascript variable to PHP

-2

My problem is that I have a button which sends a parameter to a javascript function. When I receive it in this function, I want to execute an sql query where the where includes this received variable (this to generate a pdf jspdf and not having to visualize all the fields to download). My query is if it is possible to receive this variable in PHP, because when I print the alert it shows me an empty field.

<?php 
 function prueba(dse) { //debería ir sobre el php
  $a=dse;

$q=mysql_query("SELECT id FROM tabla WHERE id='$a'");

  $ro=mysql_fetch_array($q);   
alert(<php? echo $ro['id'];?>);//deberia ir bajo del PHP              
 ?>

Thankful for answers and any alternative is valid

    
asked by Cristian Muñoz 07.09.2018 в 15:22
source

2 answers

0

I think you're confusing some concepts. The function that you published along with your question is PHP code, so I understand what you are trying to do is send a value from Javascript to a PHP file to process it on the server.

This can be done through POST server queries with AJAX .

Examples:

Javascript :

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      //Respuesta a la consulta
    }
  };
  xhttp.open("POST", "tuArchivo.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form- 
  urlencoded");
  xhttp.send("variable=valor&..."); //(en tu caso, el valor 'dse')

where in the xhttp.send("variable=valor&...") method you send the data to the server.

JQuery :

- $. post (URL, data, callback);

        $.post("tuArchivo.php",
        {
          variable:valor, //(en tu caso, el valor 'dse')
          ...
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        });

These sections can be put in the click event associated with your button to send the query with the parameters.

Then, in the file tuArchivo.php you receive it in this way:

$valor = $_POST["nombre"];

At this point you can work on the server with the variable $ value to refer to the data sent from Javascript.

This is just a simple example, I recommend this reading to get started.

    
answered by 07.09.2018 / 15:52
source
0

you must first update your php version since mysql is outdated so move to mysqli or PDO this is a good article where you will learn about it

then well to do what you want there are several ways either php or php with ajax is the most recommended and most dynamic for the user experience and here is an example

  $(document).ready(function(){

         $("#formulario").submit(function(e){//aqui obtendrias la accion del el formulario al enviarse  y asignadole el parametro e para evitar que se refresque la pagina 

            var id=$("#idVariable");//aqui recivirias el valor del input o campo que deceas para luego mandarlo a un archivo php para hacer el filtro

 e.preventDefault();//evitamos que se refresque la pagina para obtener un resultado mas dinamico
            $.ajax({
                    type: 'POST',//mandamos los datos atrves de post ya que es mas seguro 
                    url: 'tu_archivo_para_recivir_varivble_id.php',
                    data:{id:id},//enviamos el la variable id
                    success: function(data)//el success te dira si a tenido exito tu consulta
                    {
                        //Manejar la respuesta del otro php como quieras ejemplo 
                    }
                });
            })
        });

and the php where you receive the data would be so for example:

    <?php

    $id = $_POST['idVariable'];//aqui recivimos la variable id

       $sql= mysqli_query($mysqli,"SELECT id FROM tabla WHERE id='$id' ");//estoy suponiendo que la varible de tu conexion a la base de datos se llama $mysqli

      if($sql){//si la consulta sql tiene esxito ejecuta el siguiente codigo

      $row=mysqli_fetch_array($sql);//en la variable row se guardaran los datos de la consulta   

  //ejemplo puedes sacar los nombres de los campos que tienes en tu tabla e inprimirlos asi 
   echo $row["campo1"]; //esto seria el callback que se reciviaria en el success de tu archivo js

}
?>

I hope your help is welcome!

    
answered by 07.09.2018 в 16:00