Telest Telest - 1 year ago 83
Ajax Question

PHP file not found in AJAX call in Twig

I am practicing unit test for AJAX call in Symfony 2.8.

Here is my code :

QUnit.test("test dynamic fill", function (assert) {
var ajax = $("#ajax"); //my div to fill
$("#feed_the_ajax").click(function () {
url: "echo.php",
type: "POST",
data: {text: "Hello world !"},
success: function (data) {
error: function () {
assert.ok(!ajax.text() == "Hello world !", "Hello !");
assert.ok(!ajax.text() == "Hello world !", "Answer me ...");

It is located in a twig file.

echo.php file is just like this :

if($_POST['text'] != ""){
return $_POST['text'];

When I run the code, it tells me that "echo.php" is not found.

So there is two questions :

1) First, am I doing it wright to call an AJAX like this (in the twig) or should I use the Controller ?

2) Secondly, where should I put my PHP file to avoid 404 error ?

Thanks for your answers,

Answer Source


You can't put JS in the Controller.

But you can save it in a javascript file (located at app/Ressources/public/js/MyJSfile.js)

And include it in your twig template with :

{% javascripts 'js/MyJSfile.js' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

(see here :


Your echo.php should be in the web folder. (but your server configuration needs to permit it, basically when you install symfony, you redirect all requests to app.php or app_dev.php).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download