skip to Main Content
// js
<script>
    // when button clicked
    let tags = 'foo,bar';
    elem.innerHTML += `<x-post tags="${tags}"></x-post>`
</script>
// post.blade.php
@php
    var_dump($tags); // string(9) "foo,bar"
    $tags = explode(',',$tags); // exploding
    echo "<br>";
    var_dump($tags); // array(1) { [0] => string(9) "foo,bar"} 
@endphp

How can i fix it? And why this is working correctly when i writing tags="foo,bar" ?

Expecting: array with foo and bar.

Tryed: JSON.stringify(), array, array with JSON.stringify().

Actually, I’m sending a post with tags via ajax so that they load after clicking on the button, like pagination. It works without tags, but such a problem has arisen with them.

Maybe you know how i can normally send an array to a blade component like in php?

example

2

Answers


  1. Chosen as BEST ANSWER

    This can be solved by creating an additional component.
    After all, the problem is that I tried to process the string in php

    let html = '';
    html += `<x-post title=${post.title}>${post.content}`;
    tags.forEach(function(tag){
        html += `<x-tag>${tag.name}</x-tag>`;
    })
    html += `</x-post>`;
    elem.innerHTML += html;
    

  2. You’re sending tags in string literal with double quotes i.e. <x-post tags="${tags}"></x-post> and therefore it’s returning the total length of $tags 9.

    Try without double quotes,

    <script>
    //in JS
    let tags = 'foo,bar';
    elem.innerHTML += `<x-post tags=${tags}></x-post>`
    </script>
    
    // post.blade.php
    @php
        var_dump($tags); // string(7) "foo,bar"
        $tags = explode(',',$tags); // exploding
        echo "<br>";
        var_dump($tags); // array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" } 
    @endphp
    

    Hope it wll help 🙂

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