-2

To start with this. I have an associative array named $body (PHP).

Let's say I want to get the value of $body[1] or $body[2], depending on the id of an element.

So here's my code.

$(document).ready(function() {
  $('.messages').on('click', function() {
    var id = $(this).attr('id');
    $('#generic-modal-title').html('Message Preview');
    $('#generic-modal-body').html('" . $body[-concatenate id here-] . "');
  });
})"

What I tried doing (doesn't work):

$('#generic-modal-body').html('" . $body["id"] . "');
Jan Ariel San Jose
  • 690
  • 3
  • 11
  • 31
  • To start with JS, there's no associative arrays. – Teemu Feb 13 '18 at 12:49
  • @Teemu ohh, so I have to use a PHP variable inside the `[ ]`? – Jan Ariel San Jose Feb 13 '18 at 12:50
  • The array $body is a PHP variable. – Jan Ariel San Jose Feb 13 '18 at 12:51
  • Äh ... What? No ... https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – Teemu Feb 13 '18 at 12:53
  • you should use $('#generic-modal-body').html(''); – Kalaiselvan Feb 13 '18 at 12:54
  • Thank you for the link, will look at it. – Jan Ariel San Jose Feb 13 '18 at 12:54
  • `` inside your script tag should do the trick – kravis Feb 13 '18 at 12:54
  • You can't achieve what you want this way. You've to create the possible values into JS, either hardcode them, or make a static array with PHP before loading the page. You can't dynamically execute PHP at client-side. Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Teemu Feb 13 '18 at 13:01
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – kravis Feb 13 '18 at 13:11

1 Answers1

0

Check this out i have tested this working fine as you required

<?php $body = array(0 => "content") ?>

<script>
$(document).ready(function() {
  var id  = 0;
  <?php echo "var body = " . json_encode($body) .";"; ?>
  $('#generic-modal-body').html(body[id]);
});

<div id="generic-modal-body"></div>
code.rider
  • 1,891
  • 18
  • 21