12

I use Symfony3 with PhpStorm.2016.3.2 on Ubuntu16.04

I never done an AJAX request before and would like to test a call to controller from a view->to the controller->that sends an answer back to the view in JSON.

So I read on the doc but they are all very specific. So my desire is to only being able to write a simple AJAX request in a view(index.html.twig),for testing it, make a call to the controller(MainController.php) and return the answer in JSON in the view.

This is my view:

{% extends 'app/layout.html.twig' %}

{% block content %}

{% endblock %}

My controller:

class MainController extends Controller
{
    public function indexAction()
    {
        return $this->render('app/main/index.html.twig');
    }
}

I really don't want to make the job done by the others, I just want to get a hint of how to make it work. So I'm sorry if my ticket is rather empty but maybe it can help others too, like me, to know where to start off.

1 Answer 1

34

At first you need to register the route to your controller:

app_bundle_route:
    path:     /ajax_request
    defaults: { _controller: AppBundle:Main:index }

Then load jQuery in your main view, perhaps you've done it already. You need a call to action in your template, some trigger to beginn the AJAX request:

{% extends 'app/layout.html.twig' %}

{% block content %}
    <button class="ajax">click me!</button>
    <div id="ajax-results">here comes the result</div>
    <script>
        $(document).on('click', 'button.ajax', function(){
            that = $(this);
            $.ajax({
                url:'{{ (path('app_bundle_route')) }}',
                type: "POST",
                dataType: "json",
                data: {
                    "some_var_name": "some_var_value"
                },
                async: true,
                success: function (data)
                {
                    console.log(data)
                    $('div#ajax-results').html(data.output);

                }
            });
            return false;

        });
    </script>
{% endblock %}

And at least your controller is very simple:

public function indexAction(Request $request)
{
    if($request->request->get('some_var_name')){
        //make something curious, get some unbelieveable data
        $arrData = ['output' => 'here the result which will appear in div'];
        return new JsonResponse($arrData);
    }

    return $this->render('app/main/index.html.twig');
}

I think this concept should make clear how it can work

Sign up to request clarification or add additional context in comments.

15 Comments

Thank you very much for your answer, I will apply that to my work right away and letting you know how does that work (in an hour or so) Alos I should not use the if($request->isXmlHttpRequest()) for AJAX request? I thought so...
You can, its up to you how you match the request. I showed one of many options.
Ok thank you :) I will try that right away and letting you know.
Hm it is not really working :/ I tried with a var like this data: { "$test": "hello world" }, and also the url is not url:{{ (path('ajax_request')) }}, I think, I used (path('app_bundle_route')) to match it. But I can't make it work actually. @Rawburner
Don't forget use Symfony\Component\HttpFoundation\JsonResponse; in the controller.
|

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.