foreach php inside script

3

Could you please let me know if it is wrong to use this code like this:

<script type="text/javascript">
<?php foreach ($lista as $key => $value) { 
  $id_indicador = $lista[$key]['id'];
?>
    var id_indicador = <?php echo $id_indicador ?>;
    $(document).ready(function() {
      $("#collapse"+id_indicador+"1").click(function() {
        $("#collapse"+id_indicador).load('indicadores.php?id_indicador='+id_indicador);
        setTimeout( function(){ 
           $('.tooltips-grafico'+id_indicador).tooltip('show');
    }, 3000);
      });
      $('.tooltips-grafico'+id_indicador).on('hide.bs.tooltip', function (e) {
      return false;
      });
    }); <?php } ?> </script>
    
asked by anonymous 11.11.2015 / 16:34

4 answers

5

Particularly I would do it this way:

<a href="" onClick="get_indicador(<?=$row['id'];?>)">Visualizar</a>

<script type="text/javascript">

    function get_indicador(id){

        var id_indicador = id;
        $(document).ready(function() {
            $("#collapse"+id_indicador+"1").click(function() {
                $("#collapse"+id_indicador).load('indicadores.php?id_indicador='+id_indicador);
                setTimeout( function(){ 
                $('.tooltips-grafico'+id_indicador).tooltip('show');
            }, 3000);
        });
            $('.tooltips-grafico'+id_indicador).on('hide.bs.tooltip', function (e) {
                return false;
            });
        });

    }
</script>
    
11.11.2015 / 18:09
2

It is easier to use the json_encode function of PHP. So, in JavaScript, you just have to treat array converted to JSON .

Example:

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
    
11.11.2015 / 16:42
0

An example of how to go through a sequence of IDs.

The magic starts at this point list = $('[id^=foo]'); .

With this, you get an array of objects whose ID starts with "foo".

With the array in hand, just play with the information and automate all other processes related to the number that makes up the ID.

The example below is just a toggle (). Change it for the actions you want to implement.

The code is simple and I tried to put something generic and similar to the code of the question.

$().ready(function() {

	/**
	Procura todos os IDS que começam com "foo".
	*/
	list = $('[id^=foo]');

	/**
	Verifica o tamanho do array. Se for maior que ZERO, indica que encontrou objetos.
	*/
	if(list.length > 0){

		/**
		Laço de repetição para iterar o array. Equivalente ao foreach() do PHP.
		*/
		$.each(list, function(key, row) {

			/**
			Extrai o número do ID
			*/
			num = row.id.replace(/\D/g, '');

			/**
			Imprime os resultados no console.
			No Google Chrome, pressione CTRL+SHIT+I para ver o console.
			*/
			console.log('key: '+key+', id: '+row.id, num);

			$('#bar'+num).click(function() {

				/**
				Extrai o número do ID
				*/
				num = this.id.replace(/\D/g, '');

				/**
				Exibe ou oculta o objeto relacionado com ID do objeto clicado.
				*/
				$('#foo'+num).toggle();

			    /**
			    Exibe o número clicado, no console.
			    */
				console.log(num);
			});

			/**
			Oculta os objetos "foo".
			*/
			$('#'+row.id).toggle();
		});
	}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="bar1">bar</div>
<div id="foo1">foo</div>
<div id="bar2">bar</div>
<div id="foo2">foo</div>
<div id="bar3">bar</div>
<div id="foo3">foo</div>
<div id="bar4">bar</div>
<div id="foo4">foo</div>
<div id="bar5">bar</div>
<div id="foo5">foo</div>

In your code it will be a bit tricky to use this logic without modifying the ID pattern of the element that receives the click.

In elements called "collapse" that receive the click () trigger, I suggest modifying it to another name like "bar_collapse" + number.

The number must be identical to the other collapse element that invokes the load () method.

Example

<div id="bar_collapse1">
<div id="collapse1"></div>
</div>
<div id="bar_collapse2">
<div id="collapse2"></div>
</div>

This is required to make it easier to search objects list = $('[id^=bar_collapse]');

    
11.11.2015 / 18:03
0

Look at this example:

return json_encode($arr);

The printed array {"a":1,"b":2,"c":3,"d":4,"e":5} .

    $.ajax({
    type: "get",
    url: "sua_url.php",
    dataType: "json",
    success: function(json){
        $.each(json, function(key, value){
            alert(value.a + " - " + value.c);
        });
    }
});

In this example I want the value of the key a and c.

    
12.11.2015 / 13:24