Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mutaz's avatar
Level 7

Get data after submit form..

Hi everyone!! I have used axios library to submit form but , the results don't appear on page but form submitted successfully but if i refresh the page the data appear. my question : how can i get data and show it from response of form??

     <section class="mb-10 col-span-8 col-start-5 mt-10 space-y-6">

                        @include('books.__add-comment-form')
                                    @foreach($book->comments as $comment)
                                    {{-- the data i want to see here.. --}}
                            <x-book-comments :comment="$comment"/>     
                        @endforeach
                    </section>
@auth
<x-panel> 
    <form
    action="/books/{{$book->title}}/comments" method="POST"
    >
    @csrf

    <header class="flex items-center">
        <img
        src="https://i.pravatar.cc/50?u={{auth()->id()}}"
        width="50" height="50" alt=""
        class="rounded-full "
        >
        <h2 class="ml-4 font-semibold">Want to participate?</h2>
    </header>

    <div class="mt-4">
        <textarea
        class="w-full p-2 text-sm focus:outline-none focus:ring"
        name="body"
        id="body"
        rows="5"
        placeholder="Quick,think of something to say!"
        ></textarea>

        <x-form.errors name="body"/>
    </div>
    <div class="flex justify-end mt-6 pt-6 border-t border-gray-200 ">

        <x-form.button id="submit-button">Publish</x-form.button>
    </div>
</form>
</x-panel>

@else
<p class="text-blue-500 font-bold">
    <a class="hover:underline"
    href="/register">Register</a> or
    <a class="hover:underline"
    href="/login">Log in</a> to
    leave a comment.
</p>
@endauth

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
<script>
    var comments = document.getElementById('comments');
    document.getElementById('submit-button').addEventListener("click", function(event){
        event.preventDefault()
            var body = document.getElementById('body').value
            axios.post('/books/{{$book->title}}/comments', {body: body})
            .then(function (response) {
                 // here how can i get data and show it after submit the form???
        })
            .catch(function (error) {
                console.log(error);
            });
        })

    </script>
</x-app-layout>
0 likes
12 replies
Sinnbeck's avatar

Start by using console.log(response) to see what data you get returned

mutaz's avatar
Level 7

@Sinnbeck it's like that

data: "{\"body\":\"Hello\"}"

I need to show all comments witout refresh again so, how can i send the all comments varible to blade page in script code?

Sinnbeck's avatar

@mutaz then show what you return from that post request controller method (the code)

mutaz's avatar
Level 7

@Sinnbeck

  public function store(Book $book)
    {
        request()->validate([
            'body' => 'required|max:255'
        ]);

        $book->comments()->create([
            'user_id' => request()->user()->id,
            'body' => request('body'),
        ]);

        // return back()->with('flash', 'Commented Successfully');
    }
Sinnbeck's avatar

@mutaz to use the data in Javascript you need to actually return it

$book->load('comments');
return response()->json(['book' => $book]);
mutaz's avatar
Level 7

@Sinnbeck when i tried that and print data in console , it seem return all comments not for specify book ,, however, how can user this reponse and show it in laravel blade??

mutaz's avatar
Level 7

@Sinnbeck ok

 public function store(Book $book)
    {
        request()->validate([
            'body' => 'required|max:255'
        ]);
        $book->comments()->create([
            'user_id' => request()->user()->id,
            'body' => request('body'),
        ]);
        $book->load('comments');
        return response()->json(['book' => $book]);
    }

        <section class="mb-10 col-span-8 col-start-5 mt-10 space-y-6">

            @include('books.__add-comment-form')

            @foreach($book->comments as $comment)
// the data i want to added here after click the button..
            <x-book-comments :comment="$comment"/>
            @endforeach
        </section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
<script>
    var comments = document.getElementById('comments');
    document.getElementById('submit-button')
    .addEventListener("click", function(event){
        event.preventDefault()
        var body = document.getElementById('body').value
        axios.post('/books/{{$book->title}}/comments', {body: body})

        .then(response => {
            console.log(response.data)
        })
        .catch(function (error) {
            console.log(error);
        });
    })

</script>




mutaz's avatar
Level 7

@Sinnbeck

Route::post('books/{book:title}/comments', [BookCommentController::class, 'store'])->middleware('auth');
Sinnbeck's avatar

@mutaz ok so I assume titles are guaranteed unique?

Anyways, you should get a single book returned with all of its comments. You can iterate over them and append them to the dom now

mutaz's avatar
Level 7

@Sinnbeck that's ok, but how can i do that with js ,note that my code sotre comment in DB but i can't see it until refresh the page , so how can i see it automatically??

Please or to participate in this conversation.