Php and Javascript - Pass javascript array to Php function on the same page

Asked

Viewed 31 times

-4

good afternoon, I have an html with some checkbox:

            <input type="checkbox" name="item" value="UM" onclick="verificaChecks()">1
            <input type="checkbox" name="item" value="DOIS" onclick="verificaChecks()">2
            <input type="checkbox" name="item" value="TRES" onclick="verificaChecks()">3

they call javascript (I tried to call php direct but could not, I’m still learning):

<script type="text/javascript">
    function verificaChecks() {
        var ckitem = document.getElementsByName("item"); 
        var ckarray = [];
        var o = 0;

        for (var i=0;i<ckitem.length;i++){ 
            if (ckitem[i].checked == true){ 
                ckarray[o] = ckitem[i].value;  
                o++;          
            } 
        }

        for (var i=0;i<ckarray.length;i++){
            ck = ckarray[i];
            alert(ck);            
        }        
    } 
</script>

in this javascript it shows an alert with all values of checks, I need to pass this array to the php function I have on this page:

<?php
function sProjeto($ckarray){

    $projeto = $dados['projeto'];

    foreach ($ckarray as $ck):
        foreach($projeto as $proj):
            
            if($proj->$ck == 1):
                print_r($proj->DESCRICAO);
                echo '---';
            endif;           
            
        endforeach;
    endforeach;

}
?>

.. but I cannot pass the javascript array to the php function.

-- Edit I couldn’t do it with Ajax, but I could only do it with Php, created a form and passed the values by json.. vlw

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

1 answer

1

Good afternoon, it is not possible to pass the javascript data to your php function on the same page without a refresh like this. To do this, you would have to make a request for some file, thus running php, since it is server side.

Some alternatives:

1 - Create a form and submit to the same page, and calling its function with the form data

if($_POST) {
   sProjeto($_POST);
}

2 - Make an AJAX call to the same page, passing the data in POST or GET form, and when you receive this data on the same page, display them

Example using jQuery:

$.post(
   'sua_pagina_atual.php',
   { data: $('seu_formluario').serialize() }, // pega todos os values do formulário especificado
   function(data) {
        $('div_mostrando_dados').html(data) // assim você irá exibir nessa div, tudo que foi passado em um 'echo' no php
   }

And to receive this form, you use the same form cited in example 1.

I hope I’ve helped!!

Browser other questions tagged

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