2

I'm trying to use AJAX to run my controller code after a button is clicked. From what I gathered, this is what you should use AJAX for...it sends a response from the front end to the back end and then generates a json response.

However I cannot figure out how to properly do this. I'm unsure on how to get AJAX to run the controller code on success.

All I have been able to do is show the table upon success but I don't want the controller code to run until button is clicked, as that is the point of the AJAX .

Symfony does not appear to have a documentation on this: http://symfony.com/legacy/doc/book/1_0/en/11-Ajax-Integration

And these stack overflow question/answers are too old for my use or do not help me:

How to integrate Ajax with Symfony2

How to make a POST Ajax request with Symfony and Jquery

twig:

<button id="begin-check" type="button">Run Test</button>

<table class="stab">
  <thead>
    <tr>
      <th style="text-align: center">Ang</th>
      <th style="text-align: center">Lat</th>
    </tr>
    <tr>
        <th>Name &amp; Age</th>
        <th>Name &amp; Age</th>
    </tr>
  </thead>
  <tbody>
  {% for person in persons %}
        <tr>
            <td>
                <a href="{{ path('users_edit', { 'id': person[0] }) }}">
                    {{ person[1] }}, {{ person[2] }} 
                </a>
            </td>
            <td>
            {% if person[7] == 'Moe' %}
                <a href="{{ path('edit', { 'id': person[6] }) }}">
            {% else %}
                <a href="{{ path('low_edit', { 'id': person[8] }) }}">
            {% endif %}
                    {{ person[4] }}, {{ person[5] }} 
                </a>
            </td>
        </tr>
    {% endfor %}
  </tbody>
</table>

AJAX:

<script type="text/javascript">
    $(document).ready(function(){
        $(document).on('click', "#begin-check", function(e){
            console.log('You have clicked');
            e.preventDefault();
            $.ajax({
                method: 'POST',
                url: "{{ path('control_check') }}",
                data: { //research what to put here
                 },
                success: function(responseData){
                    //run the controller code
                    //Show HTML table
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(xhr.status);
                    console.log(xhr.responseText);
                    console.log(thrownError);
                },
            })
        });
    });

</script>

In controller:

/**
 *
 * @Route("/control", name="control_check")
 * @Template()
 */
public function controlCheckAction()
{
    $request = $this->get('request');
    $em = $this->getDoctrine()->getManager();

    $persons = array();

    //more code

    return new JsonResponse(array('persons' => $persons));

}
Community
  • 1
  • 1
grgre
  • 85
  • 7
  • Is your javascript code into a twig template? – Sir McPotato Jan 24 '17 at 14:00
  • It's in the same file as my twig from above – grgre Jan 24 '17 at 14:15
  • You cannot run sever side controller code from inside your javascript success function. When success is called, your responseData will have whatever json that controlCheckAction has generated. You then need javascript to render a table. See if you can find a nice intro to ajax tutorial without the complications of Symfony. You need to understand the basics first. – Cerad Jan 24 '17 at 14:50

2 Answers2

0

I think all you need to add to what you already have is the isXmlHttpRequest() method. Here's the official documentation.

So:

/**
 *
 * @Route("/control", name="control_check")
 * @Template()
 */
public function controlCheckAction(Request $request)
{
    if ($request->isXmlHttpRequest()) {
        //$request = $this->get('request');
        //replace the up line code with the folloging, which gets a particular form field
        $name = $request->request->get('name'); // <=> $name = $_POST['name']
        $em = $this->getDoctrine()->getManager();

        $persons = array();

        //more code

        return new JsonResponse(array('persons' => $persons));
    }
}
Dan Costinel
  • 1,716
  • 1
  • 15
  • 23
  • I for sure forgot to add the `Request $request` argument to the controller function...so thank you for that, but I'm confused on what would be `$request->request->get('name');` for me. I don't have a form field to use here... – grgre Jan 24 '17 at 14:28
  • Then just `dump($request)` in the `controlCheckAction()` to see what's available for you, after pressing the submit button. I don't really know what you intend to achieve. Usually in the template there is present a `
    ` which sends its data through that AJAX call.
    – Dan Costinel Jan 24 '17 at 14:35
0

Probably, I encountered the same situation.

In my case, I forgot to add "use" statement. Don't you forget to add this line?

use Symfony\Component\HttpFoundation\JsonResponse;

I attache my check point.

【1】checking server side application logs

error_log("create json response OK" . "\n", 3, "/usr/local/var/log/php/error.log");
return new JsonResponse(array('persons' => $persons));

【2】checking console debugger

open chrome debugger(F12) -> Network tab -> "/control" (left navigation)

So, you can confirm "Response header".

[OK] Content-Type:application/json
[NG] Content-Type:text/html

if you find "text/html", I think server side problem.

【3】checking symfony2 debugger

You can find symfony2 debugger url in the same tab 【2】

X-Debug-Token-Link:http://xxxxxxxxx/_profiler/xxxxx

you should open this profiler link. you can find any problems if this problem come from server side.