0

I am using twig and symfony 2.8. In a twig template I make an AJAX call to a php script. this is the simplified AJAX call:

$.ajax({
    url:'{{ (path('search')) }}',
    type: "POST",
    dataType: "json",
    data: {
        "fields": {
            "invoiceNo" : $("#invoiceNo").val()
        }
    },
    async: true,
    success: function (data)
    {

    }
});

The response data is an array containing the id of some invoices. I want to use the path function in twig to generate urls of invoices based on the IDs in data.

I did this:

for (var i = 0; i < data.length; i++) {
    var url = {{ path('invoice_url', {'invoiceId' : data[i]['id']}) }}
}

However I am getting an error that the variable data does not exist. I suppose, this is because data is a runtime variable.

any idea how I can use AJAX call result (data) to generate the urls?

6
  • 4
    Possible duplicate of Pass javascript variable to twig Commented Feb 1, 2018 at 15:21
  • @goto I'm not sure the question you linked answers this question; this question is about how to use the result of an Ajax call in Twig Commented Feb 1, 2018 at 15:26
  • This isn't possible; Twig, like PHP, is executed server-side while the Ajax call is handled entirely client-side. It's possible to find a workaround using only JS and jQuery, but you won't be able to use Twig in that way. You can also check out FOSJsRoutingBundle on GitHub Commented Feb 1, 2018 at 15:27
  • 2
    You can't pass javascript variable to twig (PHP) If you want to generate a route in javascript, you can either replace a flag in your route by javascript, or use FOSJsRoutingBundle. As answered here stackoverflow.com/questions/36291358/… Commented Feb 1, 2018 at 15:31
  • 1
    How is this possible a question about the result of an ajax call, as your ajax call is never called? Goto is correct in here, that u'd need to use FOSJSRoutingBundle to resolve the url to where u want to post your ajax-call Commented Feb 1, 2018 at 16:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.