Z
Z
zekin2020-05-28 14:03:27
PHP
zekin, 2020-05-28 14:03:27

How to marry php and js?

Please help me, there is a php code with which I get the elements

<?
if (CModule::IncludeModule("iblock")):
 
    $iblock_id = 53;
    # show url my elements
    $my_elements = CIBlockElement::GetList (
      Array("ID" => "ASC"),
      Array("IBLOCK_ID" => $iblock_id),
      false,
      false,
      Array('ID', 'NAME',  'PROPERTY_TAGS', 'DETAIL_PAGE_URL')
    );
 
    while($ar_fields = $my_elements->GetNext())
    {
      echo $ar_fields['NAME'])." ;<br>";
    }
endif;
?>


There is js

const items = [
  {
    id: 1,
    name: 'провод',
    url: 'provod',
    tags: ['провода', 'проводов']
  },
  {
    id: 2,
    name: 'робот',
    url: 'robot',
    tags: ['роботы', 'роботов']
  },
]


The task is to transfer data from the php array to JS to fill in const items according to the example as it is now, but I can’t figure out how to do it, as far as I could google that you need to wrap the php array in json and transfer it already to js, ​​but I can’t do it.

Please do not beat with sticks, please help me write the code

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Sokolov, 2020-05-28
@zekin

if JS is in the body of the page generated by PHP, then just paste it into the output:
index.php

<?php
$result = [];
while ($ar_fields = $my_elements->GetNext()) {
      $result[] = $ar_fields;
};
?>

const items = <?php echo json_encode($result); ?>;

I
Igor, 2020-05-28
@loonny

Send a GET / POST request to the address of the script from JS, after converting the response to JSON on the server, for example. Next and done. const items = JSON.parse(response)

A
Alexander Miranovich, 2020-05-28
@aleks_664

<?
if (CModule::IncludeModule("iblock")):
 
    $iblock_id = 53;
    # show url my elements
    $my_elements = CIBlockElement::GetList (
      Array("ID" => "ASC"),
      Array("IBLOCK_ID" => $iblock_id),
      false,
      false,
      Array('ID', 'NAME',  'PROPERTY_TAGS', 'DETAIL_PAGE_URL')
    );
 
    while($ar_fields = $my_elements->GetNext())
    {
      echo $ar_fields['NAME'])." ;<br>";
    }
endif;
?>
<script>
  var $my_elements = <?=json_encode($my_elements);?>
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question