2

Good day to all. I have problem with ajax request in symfony3. In this case it returns code 200 and everything ok. This is "dirty" code example, but with "good" code i am getting respond with code 500. I know that this syntax is more appropriate. So question is how to fix syntax which is applies to symfony documentation.

 /**
 * @Route("/ajax", name="ajax_handler")
 */
public function ajaxAction(Request $request) {

    if ($request->isXMLHttpRequest()) {
        if(isset($_POST['secret']))
        echo json_encode(array('ok'=>1));
        exit;
    }
}

Why if i will write appropriate to "all known" syntax code it will returns code 500?

  /**
     * @Route("/ajax", name="ajax_handler")
     */
    public function ajaxAction(Request $request) {

        if ($request->isXMLHttpRequest()) {
//            echo json_encode(array('ok' => 1));
//            exit;

            $response = new Response(json_encode(array('name' => $name)));
            $response->headers->set('Content-Type', 'application/json');

            return $response;
        }
    }

enter image description here

JavaScript:

$(document).ready(function () {

                $(".add-one-email").click(function () {

                    var data = {"test": 1};

                    data = $.param(data);

                    $.ajax({
                    type:"POST",
                            dataType:"JSON",
                            url:"/ajax",
                            data: data,
                            success:function (s) {
                                alert(s['ok']);
                                }
                    });
                });

            });

if ($request->isXMLHttpRequest()) {
        $response = new Response('sadasdasd');
        return $response;
    }

In upper case it returns 500 StuckTrace:The controller must return a response | in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php at line 171 |  if (null === $response) {
                    $msg .= ' Did you forget to add a return statement somewhere in your controller?';
                }
                throw new \LogicException($msg);
Community
  • 1
  • 1
Yevhenii Shashkov
  • 464
  • 1
  • 8
  • 19

1 Answers1

0

This syntax works good

use Symfony\Component\HttpFoundation\JsonResponse;

  return new JsonResponse(array('ok' => 1));

Problem was that i was using old syntax and looks like it is not work in symfony3, but this code works good.

Yevhenii Shashkov
  • 464
  • 1
  • 8
  • 19