How to transfer a Javascript array to a PHP array

Asked

Viewed 373 times

1

How can I transfer a Javascript array to a PHP array ?

Javascript function

array of expiration dates (datasvenc) in the registration file.php:

 function calculamensalidades(){
  var datasvenc = new Array(7);
  var tabela;
  tabela = "<br><table border='0' width='30%' style='text-align:center'><tr><td bgcolor='#4682B4'>Parcela</td><td bgcolor='#4682B4' >Valor</td><td bgcolor='#4682B4'>Vencimento</td></tr>";


  for(var a=0; a<document.getElementById("select_parcelas").value; a++)
 {
  var n_date = new Date(date.getFullYear(), eval(a+mesvencimento), diavencimento);
  var diavenc = date.getDate();
  var mesvenc = n_date.getMonth()+1;
  var anovenc = n_date.getFullYear();
     tabela = tabela + "<tr><td bgcolor='#9AC0CD'>"+(a+1)+"</td><td bgcolor='#9AC0CD'>R$ "+valorparcela.toFixed(2)+"</td><td bgcolor='#9AC0CD'>"+diavenc+"/"+mesvenc+"/"+anovenc+"</td></tr>";
     datasvenc[a] = diavenc+"/"+mesvenc+"/"+anovenc;
 }
}

I need to insert the correct expiration date for each table record in the same registration file.php:

if (isset($_GET['cadastra']) && $_GET['cadastra'] == 'add') {
  $dataVencimento = filter_input(INPUT_GET, 'datasvenc');
  $dataVencimento = unserialize(base64_decode($dataVencimento));//Decode para array
    for($numparcelas=1; $numparcelas <= $parcelas; $numparcelas++ ){
          $cadastraparcelas = $conn->prepare("INSERT INTO t_cadparcelas (NumContrato, NumParcela, ValorParcela, DataVencimento, Status) VALUES (?, ?, ?, ?, ?)");
          $cadastraparcelas->execute(array($IDultimocontrato, $numparcelas, $valorparc, $dataVencimento[1], $status));
      }

...

  • 1

    Can use JSON.stringify(array) in the JS and json_decode($_GET['array'], true); in PHP, already tested?

  • hello @Sergio thanks for the return, never tested, can post some example you can use with my code above? thanks again

  • 1

    The answer I gave was what I was looking for?

  • @Sergio helped, but I simply passed the javascript variable to an input and soon after treated the string of dates in php for insertion in the database, thanks a lot for the help!

1 answer

2


The best way to pass data between client and server is JSON.

So to encode/convert an array to JSON, or a format that functions created to interpret JSON can use is:

On the client side (Javascript):

JSON.stringify(<conteudo>); // para enviar (converter em string)
JSON.parse(<conteudo>);     // para receber (converter em Tipo)

On the server side (PHP):

json_encode(<conteudo>);           // para enviar (converter em string)
json_decode(<conteudo>[, true]);   // para receber (converter em array ou objeto dependendo do segundo parametro)

So in your code you could do:

var dadosParaPHP = JSON.stringify(datasvenc);

and on the PHP side do:

$dadosDoJavascript = json_decode($dataVencimento, true);

Browser other questions tagged

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