how to go through all elements of a php array with javascript

Asked

Viewed 667 times

0

how can I go through all the elements of a php vector in javascript because my javascript only takes the last name but my 'var_dump()' is receiving all how can I do this someone can help me?

php code:

 foreach($_SESSION['carrinho'] as $id => $qtd){
                              $sql   = "SELECT *  FROM produtos WHERE id_produto= '$id'";
                              $qr    = mysql_query($sql) or die(mysql_error());
                              $ln    = mysql_fetch_assoc($qr);

                              $nomes  = $ln['nome'];
                              $preco = $ln['preco'];
                              $sub   = $ln['preco'] * $qtd;
                              $img   = $ln['img'];
                              $desc  = $ln['descricao'];
                              $id    = $ln['id_produto']; 


                              $nomes = array($nomes);
                              $nomes = implode("|", $nomes);
                              var_dump($nomes);

                    }

javascript code:

var i, array_produtos, string_array;
        //recebe a string com elementos separados, vindos do PHP
        string_array = "<?php echo $nomes; ?>";
        //transforma esta string em um array próprio do Javascript
        array_produtos = string_array.split("|");

        //varre o array só pra mostrar que tá tudo ok
        for (i in array_produtos)
        alert(array_produtos[i]);

2 answers

1


Instance a variable outside the foreach, it is rewriting.

PHP

$final_result = "";
 foreach($_SESSION['carrinho'] as $id => $qtd){
                          $sql   = "SELECT *  FROM produtos WHERE id_produto= '$id'";
                          $qr    = mysql_query($sql) or die(mysql_error());
                          $ln    = mysql_fetch_assoc($qr);

                          $nomes  = $ln['nome'];
                          $preco = $ln['preco'];
                          $sub   = $ln['preco'] * $qtd;
                          $img   = $ln['img'];
                          $desc  = $ln['descricao'];
                          $id    = $ln['id_produto']; 

                          $final_result .= "|" . $nomes;

                }

Java Script:

var i, array_produtos, string_array;
        //recebe a string com elementos separados, vindos do PHP
        string_array = "<?php echo $final_result; ?>";
        //transforma esta string em um array próprio do Javascript
        array_produtos = string_array.split("|");

        //varre o array só pra mostrar que tá tudo ok
        for (i in array_produtos)
        alert(array_produtos[i]);

Below is a smarter way to obtain the data.

PHP (Take all data and convert into json)

$final_result = array();
foreach($_SESSION['carrinho'] as $id => $qtd){
        $sql   = "SELECT *  FROM produtos WHERE id_produto= '$id'";
        $qr    = mysql_query($sql) or die(mysql_error());
        $ln    = mysql_fetch_assoc($qr);

        //Não sei se já existe quantidade em banco mas caso não exista estou setando ela manualmente abaixo:
        $ln['quantidade'] = $qtd;

        //Detalhe todos os campos do banco já estão no vetor inclusive nome img descricao etc...

        array_push($final_result, $ln);
}

$fjson = json_encode($final_result);

Javascript

var i, produtos;
//recebe o objeto json do php
produtos = <?php echo $fjson; ?>;

//varre o array só pra mostrar que tá tudo ok
for (i in produtos)
{
    alert("Nome: " + produtos[i].nome + "\nQuantidade: "+produtos[i].quantidade);
}
  • intendi thank you very much

  • this way that Voce explained there is no way to do type for him to get the quantity of product type the product 1 has 2 quantity and the product 2 has 3 quantities. That way it will print like this: product1 | product 2 2 | 3 wouldn’t have as I print respectively? ex: product 1 quantity 2 | product 2 quantity 3 ?

  • Then the correct thing would be for you to make use of json, and convert it to a javascript object

  • I’ll edit the answer.

  • Ready the answer is adapted

  • in Alert the quantity enters as Undefined type has no problem because I will send to email by ajax?

  • the quantity was not in the vector... I already arranged again the answer

  • or give a +1 ai in the answer now it is more complete

  • Of course I’ll give you +1

  • worked the amount?

  • ran agr am trying to send the data via ajax

  • Do you know how I feel when I click to finalize the purchase he send me an email and at the same time call the form of the pagseguro passing the total amount of the purchase I can not do because of the action of pagseguro you have any idea? type so I’ll just send the total amount to the pagseguro and this example you answered to get all the data I will pass by email

  • So @Leonardocosta this would be another question, but look for PHP Mailer and the use of AJAX.

  • type guy I know how to do this I already use php for a long time Mailer and ajax tbm I have several things using the 2 but d good face vlw by Resp ai

  • need only ask ;)

  • Since Javascript was used, it would be good to keep the languages separate from each other, based on how they operate.

Show 11 more comments

0

Here’s an example of how you could do this using php’s json_encode function:

<?php

$nomes = array(
  'nome1',
  'nome2',
  'nome3',
  'nome4',
  'nome5',
);

?>

<script type="text/javascript">

var nomes = <?php echo json_encode($nomes); ?>;

for (var nome in nomes) {
  console.log(nomes[nome]);
}

</script>

json_encode: This function returns a json-shaped representation of the variable that is passed as it argues to it. In the above example it will return the string below, which in javascript is interpreted as an array:

["nome1","nome2","nome3","nome4","nome5"]

Applying this function to your code, it could look like this:

<?php

$result = array();    

foreach($_SESSION['carrinho'] as $id => $qtd){
  $sql   = "SELECT *  FROM produtos WHERE id_produto= '$id'";
  $qr    = mysql_query($sql) or die(mysql_error());
  $ln    = mysql_fetch_assoc($qr);

  $nomes  = $ln['nome'];
  $preco = $ln['preco'];
  $sub   = $ln['preco'] * $qtd;
  $img   = $ln['img'];
  $desc  = $ln['descricao'];
  $id    = $ln['id_produto']; 

  $result[] = $nomes;

}

?>

<script type="text/javascript">

var i, array_produtos;
//recebe a string com elementos separados, vindos do PHP
array_produtos = <?php echo json_encode($result); ?>;
//transforma esta string em um array próprio do Javascript

//varre o array só pra mostrar que tá tudo ok
for (i in array_produtos)
    alert(array_produtos[i]);

</script>
  • not right to do it this way he keeps returning the last number

  • I edited the script now should work.

Browser other questions tagged

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