Passing variables from a javascript to an html

0

Hi, I have the following jquery script:

    <script type="text/javascript">
       $(document).ready(function(){
        $("a").on("click", function() {
        var img = $(this).children('img').attr('src');
        var p = $(this).children('p').text(); 
        });
       });
   </script>

That collects the data of:

  <a href="#">
   <img src="img/bebe.jpg" alt="">
   <p>prueba 1</p>
  </a>
  <a href="#">
   <img src="img/taller.jpg" alt="">
   <p>prueba 2</p>
  </a>

I want to send those javascript variables to another HTML page.

    
asked by PiledroMurcia 23.01.2018 в 12:12
source

5 answers

3

Well you do a GET or a POST passing the data you want to the server (PHP).

EXAMPLE with POST (better for the data you want to pass)

   $(document).ready(function(){
    $("a").on("click", function() {
    var img = $(this).children('img').attr('src');
    var p = $(this).children('p').text();

    $.ajax({
        type: "POST",
        url: '/tu/url',
        data: {'img':img,'p':p},
        success: function(data) {
          //success actions
        },
        dataType: 'json'
      });
    });
   });

If the fields to be passed are inside a form, the data can be directly

data : $('#<mi_form_id>').serialize()
    
answered by 23.01.2018 в 12:26
1

You could use the LocalStorage API to avoid having to go through PHP.

For example:

<script>

   //A esta funcion de abajo la llamas cuando veas necesario, despues de un click podría ser tu caso, recibe dos parametros, el src que capturaste y el texto del parrafo. 
   $(document).ready(function(){

   function poblarLocalStorage(vsrc,vparrafo){

      localStorage.setItem("srcLlamada",vsrc); //src es el nombre por el cual accederemos
      localStorage.setItem("parrafoLlamada",vparrafo); //ParrafoLlamada lo mismo.
   }



    $("a").on("click", function() {
    var img = $(this).children('img').attr('src');
    var p = $(this).children('p').text(); 

    //***Aqui llamo a la funcion que realicé **//

    poblarLocalStorage(img,p);  //Img y p son las variables que capturaste
    });
   });

 </script>


  //Ahora para llamar a esas variables en otra ventana. 
  <script>
  $(document).ready(function(){

   //Suponiendo que tenes unos Id en unos nuevos <p> y <img>

   function recuperarDatosLocalStorage (){

      var img = document.getElementById("imagen");
      var parrafo = document.getElementById("parrafo");

      img = localstorage.getItem("srcLlamada");
      parrafo = localstorage.getItem("parrafoLlamada")
   }

   //Llamo a la funcion RecuperarDatos.

    recuperarDatosLocalStorage();
  });
<script>
    
answered by 23.01.2018 в 15:01
1

Let's see what I start to see mess of concepts. To begin with

$(document).ready

implies what jQuery is using.

Then, "from javascript to HTML" implies what you do not want processed on the server side? that is, the element will simply modify some other element of the DOM (HTML already generated) before clicks? To give you a silly example: A text box that shows the SRC attribute of the img and an element > what also:

$("a").on("click", function() {
    var imgSrc = $(this).children('img').attr('src');
    $('#myinputID').val(imgSrc);
    $('#myspanID').html(imgSrc);
});

Each element of the DOM (HTML) will be instantiated accordingly.

So far I do not see any need for additional local-style libraries.

Although I have speculated because I no longer see very clearly what you are looking for. If you specify a little more we can help you better:)

    
answered by 23.01.2018 в 20:51
0

Given the comment I rectify, my problem is to send those javascript variables to an html page I update my response.

To pass a javascript variable from one html page to another you can use localStorage .

So you add a variable to localStorage :

localStorage.setItem("nombre_variable",variable);

And so you get it:

localStorage.getItem("nombre_variable");
    
answered by 23.01.2018 в 12:30
0

To communicate between pages you must use the forms.

They can go through GET or choose by the form POST method.

  

Startpage.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<form action="PaginaDos.html" name="FormEnvioDatos" id="FormEnvioDatos" method="get">

    <a href="#">
        <img src="img/bebe.jpg" alt="">
        <p>prueba 1</p>
        <input type="hidden" id="Prueba1" name="Prueba1" value="Prueba 1" />
    </a>
    <a href="#">
        <img src="img/taller.jpg" alt="">
        <p>prueba 2</p>
        <input type="hidden" id="Prueba2" name="Prueba2" value="Prueba 2" />
    </a>
    <input type="hidden" id="imgDesdeLaPagina1" name="imgDesdeLaPagina1" value="" />
</form>

<script type="text/javascript">
    $(document).ready(function () {

        jQuery('a').click(function () {
            var imgSrc = $(this).children('img').attr('src');
            $('#imgDesdeLaPagina1').val(imgSrc);
            document.getElementById("FormEnvioDatos").submit();
        });

    });
</script>
  

PageDos.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<img id="ImagenPintar" src="" />
    <script type="text/javascript">
    $(document).ready(function () {
        var urlParamImagen = ObtenerValorDelaImagen("imgDesdeLaPagina1");

        $("#ImagenPintar").attr("src", urlParamImagen);
        function ObtenerValorDelaImagen(sParam) {
            var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;

            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {

                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        }
 });
    </script>
    
answered by 23.01.2018 в 21:28