How to pass Javascript array for PHP variable

Asked

Viewed 3,432 times

0

What is the best way to transfer two arrays in Javascript for variables in PHP, follow my idea below, it would work?

Javascript function

  • array of expiration dates (datasvenc) in the archive cadastro_contratos.php:

It is correct the creation of the array in Javascript and its attribution in the indexes within for?

function calculamensalidades(){

  var valortotal = parseFloat(document.getElementById("total").value);
  var valorparcela = valortotal/document.getElementById("select_parcelas").value;
  var parcelas = parseFloat(document.getElementById("select_parcelas").value);
  var date = new Date();
  var mesvencimento = date.getMonth();
  var diavencimento = date.getDate();
  var datasvenc = new Array(6) 
  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 diavec = date.getDate();
  var mesvenc = n_date.getMonth();
  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'>"+diavec+"/"+mesvenc+"/"+anovenc+"</td></tr>";
     datasvenc[a] = diavec+"/"+mesvenc+"/"+anovenc;
 }
 tabela=tabela+"</table>";
document.getElementById("mensalidades").innerHTML="";
document.getElementById("mensalidades").innerHTML=tabela;
 }

function apagatabela(){
document.getElementById('mensalidades').innerHTML="";
}

 function liberar()
{
  var total = document.getElementById("total"); 
  var parcelas = document.getElementById("select_parcelas");

  if(total.value != "")
  {
    parcelas.disabled=false;
  }
}

Attracting php in the same registration file.php:

this is the correct javascript assignment for php? $dataVencimento = unserialize(base64_decode($dataVencimento));//Decode para array

<div id="painelcadastro2" align="center">
<?php   if (isset($_GET['cadastra']) && $_GET['cadastra'] == 'add') {
  $datacompra = implode("-", array_reverse(explode("/",$_GET['datacompra'])));
  $nomeProduto = filter_input(INPUT_GET, 'nomeProduto1');
  $qtProduto = filter_input(INPUT_GET, 'qtProduto1');
  $valorProduto = filter_input(INPUT_GET, 'valorProduto1');
  $valorparc = filter_input(INPUT_GET, 'valorparcela');
  $parcelas = filter_input(INPUT_GET, 'select_parcelas');
  $entrada = filter_input(INPUT_GET, 'entrada');
  $total = filter_input(INPUT_GET, 'total');
  $status = "ativo";
  $dataVencimento = filter_input(INPUT_GET, 'datasvenc');
  $dataVencimento = unserialize(base64_decode($dataVencimento));//Decode para array
  $pagamento = "CREDIARIO";
  mysqli_query("SET AUTOCOMMIT=0");
  mysqli_query("START TRANSACTION");
  $cadastracontratos = mysqli_query("INSERT INTO t_cadcontratos (Ficha, DataContrato, QuantParcelas, ValorContrato, Entrada, Saldo, DescricaoProduto, QuantProdutos, Vendedores, FormaPagamento) 
                          VALUES ('$nrFicha', '$datacompra', '$parcelas', '$valorProduto', '$entrada', '$total', '$nomeProduto', '$qtProduto', UPPER('$_SESSION[MM_Username]'), '$pagamento')");
  for($numparcelas=1; $numparcelas>$parcelas; $numparcelas++ ){
  $cadastraparcelas = mysqli_query("INSERT INTO t_cadparcelas (NumContrato, NumParcela, ValorParcela, DataVencimento, Status) 
                          VALUES ('$NumContrato', '$numparcelas', '$valorparc', '$dataVencimento[numparcelas]', '$status')");
  }
  if($cadastracontratos == '1' && $cadastraparcelas == '1') {
        mysqli_query("COMMIT");
        echo "Venda Crediário realizada com sucesso !";
  }else{
        mysqli_query("ROLLBACK");
        echo "Erro ao realizar a venda Crediário, tente novamente !";
  }
}
?>

<form id="adicionarformProdutos" method"post" action"" enctype="multipart/form-data">
     <a href="#" id="adicionarProduto">Adicionar Produto</a>      
    <fieldset class="fieldsetProduto">
        <legend>Produto 1</legend>
        <div class="produtos">
            <label for="codProduto1">Código:</label><input class="codigoProduto" type="text" id="codProduto1" size="5" name="codProduto1" />
            <label for="nomeProduto1">Nome:</label> <input type="text" id="nomeProduto1" name="nomeProduto1" size="9"  />
            <label for="qtProduto1">Qt.:</label> <input type="text" size="1" id="qtProduto1" name="qtProduto1" onblur="calcValor()" />
            <label for="valorProduto1">Valor und. R$:</label> <input type="text" id="valorProduto1" name="valorProduto1" size="6" onkeypress="mascara(this,float)" />
        </div>
     </fieldset>
<br>
            <label>Data da Compra <input name="datacompra" type="text" id="datacompra" size="6" maxlength="10" value="<?php echo date('d/m/Y')?>" onKeyUp="javascript:somente_numero(this);" onkeypress="formatar_mascara(this,'##/##/####')"/></label>
            <label>Desconto (%)<span style="display:none" id="sp_vdesconto"></span><input type="hidden"  name="vdesconto" id="vdesconto" />:<input type="text" name="desconto" size="6" value="0"id="desconto" onblur="calcValor()" /></label>   
            <label>Entrada R$<span style="display:none" id="sp_vdentrada"></span><input type="hidden" size="6" name="vdentrada" id="vdentrada" />:<input type="text" name="entrada" size="6" value="0"id="entrada" onKeyPress="return(MascaraMoeda(this,'.',',',event))" onblur="calcValor()" /></label>
<div>
  <br>
  <div>
            <label>Valor Total: <input type="text" name="total" value="0" size="6" id="total" onblur="liberar(); "/></label>
            <label>Qt. Parcelas: </label><select onchange="calculamensalidades()" disabled="disabled" value="" id="select_parcelas" name="select_parcelas">
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
              <option>6</option>
            </select>
 <div id="mensalidades"></div>
</div>
<br>
    <input type="reset" onClick="apagatabela()">
    <input type="hidden" name="cadastra" value="add"  />
    <input type="hidden" value="<?php echo $nrFicha;?>" name="cadastro" />
    <input type="submit" name="add" id="add" value="Cadastrar" />  
</div><!--fechando div painelcadastro2-->
</form><!--fechando div painelcadastro2-->

2 answers

1

Add this function within your calculation method.

enviarViaAjax(){
    var dados = "&datasvenc=" + datasvenc; //Aqui você passa o array e as demais variáveis
    var xmlhttp; //Requisita o ajax
    if (window.XMLHttpRequest)
       xmlhttp=new XMLHttpRequest(); //se chrome/firefox/op vai usar XMLHttpRequest()
    }
    else
    {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //se  IE ActiveXObject
    }

    xmlhttp.open("POST","arquivo.php",true);//Informa seu arquivo.php 
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(dados);//Envia os dados
  }

In the.php file

$dataVencimento = $_POST["datasvenc"]; //Pega a info via post
$dataVencimento = unserialize(base64_decode($dataVencimento));//Decode para array

Ai just call your sql to save the value. There in javascript for you to send the rest of your variables you do this:

// var data = "&variable=" + variable + "&variable2=" + variable2;

  • Hello Vinicius, thank you! in fact in my code the javascript function is executed when I choose the number of installments so that an interactive table is generated, but how can I insert the json request without a Ubmit in my calculator function() ?

  • Hello, in case you want to send this to the server side without database ?

  • That, I want to send to a PHP variable that is on the same page, so that later include in the database the other PHP variables, I wait!

  • There I understand!!! 5 minutes please.

  • In case then, I’ll put an extra function within your calculator that will do it for you.

  • I think that’s it, anything we are there. It’s the tip to work with jquery, it already comes with standard ajax that makes your life a lot easier. rsrsrs

  • I understood, but we don’t need the.php file because the php variable is in the same javascript function file... so I could ignore the " xmlhttp.open("POST",".php file",true);//Informs your.php file " ? Can you illustrate how I would look in my job? because in the javascript function I have a for that I need to add to each repeat the due date... Thanks!

  • Can you let me know if the creation of the array and the date assignment in its indexes is correct? Thank you very much!

  • In case you should use the post and pass the name of your own file instead of the /.php file. You say the assignments of your code?

  • ok, that! in case the array creation and the assignment inside the for :)

  • Friend, I edited the above question, only in that way would it work? thanks!

  • Your code is ok yes! For nothing. Hug

  • counting on the php ? part will correctly adhere to the ? Tks indexes

  • This here you do after picking up a POST request. $Due Date = unserialize(base64_decode($Due Date)); . Where is the rest of your php code that will save this data? How are you sending this to the database ?

  • Okay, so I put in the question what do I do with this data and the rest and I put it in the database, is that correct? However this occurring error in $cadastraparcelas because it does not seem to locate the variable... But there has to do with what we are seeing

Show 10 more comments

1

Experimete use jquery, follow example below:

var numeros = [0,1,2,3,4,5,6,7,8,9];
var letras = ['a', 'b','c','d'];
$.ajax({
   url : "arquivo.php" ,
   dataType : "json" ,
   data : {
       letras : letras ,
       numeros : numeros 
  },
success:function(){} ,
error : function(){}
});

PHP

<?php
    $numeros = $_REQUEST['numeros']; //Recebe numeros;
    $letras = $_REQUEST['letras'];  //  Recebe letras;

    print_r($numeros);
    print_r($letras);
//Faz o que tem que fazer e retorna em json

    return json_encoder($numeros);

?>

More information on the jquery.com website

http://api.jquery.com/category/ajax/

  • Hello Douglas, thank you! you can give me an example with both variables in the same file, without needing to link to another url in php... direct a post and anyway ? Tks

  • @Rafaelassmann did not understand what you need so let’s rephrase: Do you need to know how to send some data to a PHP (external) file? If so, just follow the example I gave you. But if not, please explain to me again what you want.

  • internal, I have the javascript function at the top of my.php file and just below the insertion into the php database and one of the variables need to capture this javascript(array) function and pass it to php to then insert it into the database, understood ? Can you help me? Tks

  • I can, of course. The first thing you should do is separate the logic of HTML, then you will assemble a form with all the information you need and finally (By clicking the submit button, you will make a logic in js to take all the form information and send it to the PHP file via $.ajax. ? If you wish I will make an example for you. Anything just ask.

  • already do this, I take some fields of the html form and do some calculations via javascript and insert in the php variables to then insert in the database, but my problem is in the array (I don’t know if this is correct), I posted the rest of my code in the question to be clearer, hug!

Browser other questions tagged

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