Home > Net >  AlpineJS pass an array from php to x-init
AlpineJS pass an array from php to x-init

Time:01-28

I am currently working on a project that involves utilizing PHP and MySQL for data retrieval, and Alpine.js for dynamic front-end interactions. My goal is to pass the array returned from my data fetch in MySQL to the x-init function in Alpine.js, as I am relatively new to using this JavaScript framework. I would like to include what I have accomplished so far:

data.php

<?php

function dbConn() {
  //   some database connection here using PDO...

}

function getPosts() {
    return db()->query('SELECT u.username,p.* FROM users u JOIN posts p on u.id = p.user_id')->fetchAll(PDO::FETCH_ASSOC);

}

index.php

<?php


$results = getPosts();

print("<pre>".print_r($results,true)."</pre>");

?>

<div x-data="posting()" x-init="fetchPost(<?php json_encode($results); ?>)">

    <template x-for="post in posts" :key="post.id">
        <h2 x-text="post.title"></h2>
        <p x-text="post.content"></p>
    </template>

</div>

app.js

document.addEventListener("alpine:init", () => {
    Alpine.data("posting", () => ({
        fetchPost: (data) => {
            this.posts = data;
            console.log(this.posts);
        },
        posts: [],
    }));
});

Here is the result on my console and above is my array structure: screenshot of my array and console

thank you in advance!

CodePudding user response:

You almost got it right. You forgot to use echo.

<div x-data="posting()" x-init="fetchPost(<?php echo htmlspecialchars(json_encode($results), ENT_QUOTES, 'UTF-8', true) ?>)">
  • Related