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

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

HTML SECTION:

<?php $id = $row['id']; ?>
 <?php $from = $row['r_a']; ?>
 <?php $to = $row['r_b']; ?>
 <?php $dis = $row['r_dis']; ?>
 <td> 
              
 <?php 
 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>";
 ?>
 </td>

JavaScript SECTION

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

    }

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
error

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

1 Like

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…

2 Likes

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){
                e.preventDefault();
		$(this).css({opacity:0.3});
                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);
	});
});
2 Likes
<?php
$data = array('name'=>'Foo','age'=>24,'gender'=>'Male');
?>
<button type='button' onclick=getInfo('<?= json_encode($data) ?>')>INFO</button>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.