How do I pass multiple values of PHP variables to JavaScript?

This is how I performed this task and my code is given below?


<?php $id = $row['id']; ?>
 <?php $from = $row['r_a']; ?>
 <?php $to = $row['r_b']; ?>
 <?php $dis = $row['r_dis']; ?>
 echo "<a href='#' onclick = toEdit({$id},'$from','$to',{$dis})   data-toggle='modal' data-target='.bs-example-modal-sm' name='submit' class='badge badge-light btn'>Edit</a>";

JavaScript SECTION

<script type="text/javascript">
    function toEdit(id,f,t,dis) {


but alert is not working And I think probably it’s not working due to this unexpected “Quotations”
This is unexpected Quotation Image in inspect Element

You could use some form of encoding to remove the problem with quotation marks and other “special” characters.

Why do you accept quotation marks in the $to value?
Makes me feel like there needs to be some cleanup on data entry, rather than on retrieval…

1 Like

This scheme works well for me. I create a JSON encoded array of values and embed that as data attribute of the clickable button, so that Java can parse that array. In your case there is already an array $row that can be encoded and passed:

$row_json = htmlspecialchars(json_encode($row));
echo '<button id = "edit_button" data-json = "'.$row_json.'" class = "prettyclass">Edit</button>";

and then in Java --I’m in WP so I use jquery–

jQuery(document).ready(function ($) {
        $(document).on('click', '#edit_button', function(e){
                id = parseInt($(this).data('json').id, 10)
		alert('id = '+id);
                dis = $(this).data('json').dis;
                // or to reference it anywhere...
                dis = $('#edit_button').data('json').dis
                alert('dis string is '+dis);
1 Like