foreach php inside <script>

Asked

Viewed 721 times

3

Could you tell me if the use of this code is wrong:

<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>
  • 1

    That doesn’t make much sense because you’ll be writing in HTML/script var id_indicador several times, and this causes the variable to be rewritten. And repeating a lot of code unnecessarily. Can you explain what you intend to do? It seems to me that passing this PHP array/object to an array/object in javascript would be better, and then iterating in javascript.

  • This may be interesting, but I don’t know how to pass the array/object to array/object in javascript. Could you help me?

  • There really is no logic, since Javascript and PHP operate on different sides. You can always request values from PHP, and put them in the loop.

  • They could help me then pass the array/object to array/object in javascript?

  • Explain better what you intend to do exactly. Based on this script you have passed, you can not understand much.

  • Before the code was like this: https://jsfiddle.net/g273jq25/. However, for each new indicator, I have to add the codes manually. This way I’m trying, wanted to bring the codes of all indicators in the array, and automatically generate javascript code.

  • There’s the part that contains the HTML ?

  • I think I get it. You can solve it with javascript/jquery only.. I’ll post it as an answer.

  • OK. On hold.

  • I updated the HTML here https://jsfiddle.net/g273jq25/2/

  • Guys, somebody got something?

  • 1

    want express service ? ... "ok, in the waiting" would sound better as , "please thank you".. and "personal, someone got?" nor should there be any...

  • So? Where’s the feedback? It’s been 12 minutes.. Rsrs, I’m on hold

  • Sorry for the embarrassment, Daniel. I didn’t mean to be rude.

Show 9 more comments

4 answers

5


Personally I would do it that 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>
  • It works too. It’s not wrong. But in this case, Document.ready is unnecessary. A drawback of this technique is to leave the HTML code "dirty". Another point is that the passage $("#collapse"+id_indicador+"1") diverges from the second code that AP posted where it shows that concatenation is not always number 1.

  • Yes, true... it was just a suggestion

  • Sorry ignorance friends, however, I am very weak in the matter of javascript. I’m trying the way you showed me in this code, but I still can’t make it work. My code, the way it is, even though it’s crooked, is the closest I’ve come to making it work. The strange thing is that only the last 'accordion' works correctly and calls the load method. Regardless of how many indicators I carry, it is always the last that works.

  • 1

    Dude, I was wrong. You’re totally right in your answer. I just needed a few tweaks and it worked correctly.

2

It is easier to use the function json_encode PHP. Then, in Javascript, just do the processing array converted to JSON.

Example:

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

echo json_encode($arr);
  • How can I treat this in javascript Henrique? would have some example?

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.

0

An example of how to traverse a sequence of Ids.

The magic begins 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 number-related processes that make up the ID.

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

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

$().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>

<div id="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 little complicated to use this logic without modifying the ID pattern of the element that receives the click.

In the elements called "Collapse" that receive the click() Trigger, I suggest changing to another name like "bar_collapse"+numero.

The number shall be identical to the other "Collapse" element invoking the load method().

Example

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

This is necessary to facilitate the moment of searching the objects list = $('[id^=bar_collapse]');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.