简体   繁体   中英

convert JS var to PHP and vice versa

Here I am getting values from textarea in array variable.

After that I convert javascript variable to PHP variable and perform some processing over it.

After process completed again I convert PHP to JS and alert. But when I alert, it gives empty result.

<script>
    $( "#convert" ).click(function() {
        var arabic = document.getElementById("ar").value; // ar is id of text area          
        <?php $ar_terms = "<script>document.write(arabic)</script>"?>           
        <?php
        $string=implode(",",$ar_terms);    
        $result = array();    
        foreach ($ar_terms as $term) {             
           // echo $Arabic->ar2en($term);    
            array_push($result, $Arabic->ar2en($term));                    
        }    
        $result=implode(",",$result);
        ?>
        var arabic = new Array();
        arabic='<?php echo $result; ?>';
        alert(arabic);
    });
</script>

Entire code is here : https://gist.github.com/karimkhanp/d4ac41fa864fd8ae0521

You can do one thing in this scenario to pass the variable from PHP to js. You can convert the array using json_encode() before echoing:

    $result=json_encode( implode(",",$result) );

As a result, when you assign this variable to js in the <?= ?> block, it will read the json string and thus the array will be assigned:

    arabic='<?php echo $result; ?>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM