S
S
Stanislav Shendakov2020-08-03 09:02:15
symfony
Stanislav Shendakov, 2020-08-03 09:02:15

How to correctly execute ajax request in Symfony?

I continue to study Symfony 5. There is a web page with news. At the bottom of the page is a list of comments, below them is the textarea "Comment text" and the "Submit" button with the code:

<input class="btn" value="отправить" data-path="{{ path('ajax_add_comment') }}" type="button">

The functionality, I think, is clear, you can leave comments on the news. Next, the following should happen:
- the comment is written to the database
- the inscription "Thank you! We will check the comment and post it in the near future" appears under the button,
or "You must enter the comment text" if the textarea is empty.
- after moderation, the comment is displayed in the list of comments.

There are no redirects after submitting a comment.

I did it the old fashioned way:
the included javascript file says:
$( function()
{
  let but = $('.btn')
  $( but ).bind('click', but_click )
  ...
function but_click()
{
  let comment = $('#addComment').val()
  let url= $( this ).data('path')

  $.ajax({
        type: "POST",
        url: url,
        data: {
        	comment : comment,
        },
        success: function(response) {
          ...
        }
    });
}
}

And there is a controller:
...
    /**
     * @Route("/ajax_add_comment", name="ajax_add_comment")
     */
    public function addComment(Request $request, RouterInterface $router ): Response
    {
        $comment_text = $request->request->get('comment');
     // запись в БД
...

Those. the path for the ajax request is taken from the existing "ajax_add_comment" root. Everything works as intended, but there are questions:

- I feel that this approach is conceptually wrong, in relation to Symfony.
- it is possible to refer to the /ajax_add_comment route in the browser address bar, you have to do additional checks

How to make ajax requests in Symfony according to the described scheme of working with the UI. I searched the net, but have not yet found a suitable option. Almost everything is related to forms, submit, subsequent redirect, etc., etc. Please suggest the rightway :-), or share links on the topic. Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question