skip to Main Content

I want to integrate the const data variable into the php file externally. What code does it do? I am changing the data on my php page to json format, but how do I pull it into the javascript page?

User.js File:

const data = {users: [
{
  id: 1,
  fullName: 'Galen Slixby',
  company: 'Yotz PVT LTD',
  role: 'editor',
  username: 'gslixby0',
  country: 'El Salvador',
  contact: '(479) 232-9151',
  email: '[email protected]',
  currentPlan: 'enterprise',
  status: 'inactive',
  avatar: '',
},

],
}

User.php file:

$response = []; $response['users']=[]; foreach($firmalar as $firma){ $response['data'][] = [
  "avatar"=>"",
  'id'=> $firma['id'],
  'responsive_id' => '',
  'full_name'=> $firma['firma_adi'],
  'email'=> $firma['firma_mail'],
  'role'=> $firma['firma_sektor'],
  'current_plan'=> $firma['firma_telefon'],
  'status'=> $firma['firma_tehlike']


]; }   echo json_encode($response);

2

Answers


  1. Chosen as BEST ANSWER

    response()->json($result); is the solution!


  2. IIUC the structure you’re aiming for require to map it in PHP.
    So you have an object with one element users and value – array of objects (potentially users). Keeping that in mind you should have same thing in PHP before encoding.

    <?php
    
        $json = new stdClass();
        $json->users = [];
         
        $firmalar = [
            [
               'id' => 1,     
               'firma_adi' => 'firma_adi',     
               'firma_mail' => 'firma_mail',
               'firma_sektor' => 'firma_sektor',
               'firma_telefon' => 'firma_telefon',
               'firma_tehlike' => 'firma_tehlike',
            ],     
        ];
         
        foreach($firmalar as $firma)
        { 
            $user = new stdClass();
            $user->avatar = "";
            $user->id = $firma['id'];
            $user->responsive_id = '';
            $user->full_name = $firma['firma_adi'];
            $user->email = $firma['firma_mail'];
            $user->role = $firma['firma_sektor'];
            $user->current_plan = $firma['firma_telefon'];
            $user->status = $firma['firma_tehlike'];
            
            $json->users[] = $user;
        }
    
        echo json_encode($json);
    
        //or if you want that data available in your js file simply generate valid JS statement for assigning produced json to (in you case) constant BEFORE loading the JS file
        echo 'const data =''.json_encode($json).''';
    

    Please follow json_encode documentation for more details on usage.

    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search