Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple AJAX request to controller - Symfony3

Tags:

ajax

symfony

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.

like image 468
chicken burger Avatar asked Feb 14 '17 08:02

chicken burger


1 Answers

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

like image 70
Rawburner Avatar answered Sep 28 '22 06:09

Rawburner