1

I've created a Ajax request who posts data to a Symfony path. Inside my Symfony path I want to use a Javascript variable to generate my route.

$(document).ready(function () {
            function cbOnClick(cb) {
                cbValue = cb.checked;
                todoId = cb.getAttribute('data-id');

                $.ajax({
                    url: '{{ (path('change_todo_status', {'todo_id': todoId})) }}',
                    type: "POST",
                    dataType: "json",
                    data: {
                        "status": "cbValue"
                    },
                    async: true,
                    success: function (data) {
                        console.log(data)
                    }
                });
                return false;
            }
        });

Inside my url I want to set the todoId, but I'm getting te error the variable "todoId" does not exists.

Rami
  • 27
  • 8

1 Answers1

0

In '{{ (path('change_todo_status', {'todo_id': todoId})) }}', twig expects a twig variable. I already had that issue and I used a placeholder to be replaced in javascript.

In example :

let todoId = cb.getAttribute('data-id');
/*
 * this will generate a path with ReplaceMeWithCorrectValue instead of the correct value.
 * You have to use a placeholder that correspond to the restrictions defined in your route.
 */
let url = "{{ (path('change_todo_status', {'todo_id': 'ReplaceMeWithCorrectValue'})) }}";

url = url.replace("ReplaceMeWithCorrectValue", todoId);

And then, in your ajax :

$.ajax({
        url: url,
   // the remain of your code
Cid
  • 14,968
  • 4
  • 30
  • 45