无法在Symfony中进行Ajax调用

时间:2016-03-12 15:50:31

标签: json ajax symfony

我想通过ajax调用处理用户注册。因此,我创建了一个注册类(定义为服务),它将被加载到不同的控制器中:

   public function loadRegisterForm($request)
    {
        $user = new User();
        $form = $this->createForm(RegistrationType::class, $user, array('attr' => array('class' => 'ajaxRegisterForm',)));
        $form->handleRequest($request);

        $errors = "";

        $parametersArray['result'] = "";

        if ($form->isSubmitted())
        {
            if ($form->isValid())
            {
                $password = $this->get('security.password_encoder')
                    ->encodePassword($user, $user->getPlainPassword());
                $user->setPassword($password);

                $user->setIsActive(1);
                $user->setLastname('none');

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();


                $parametersArray['result'] = new JsonResponse(
                    array(
                        'message' => 'Success! User registered!',
                        'result'  => $this->renderView('ImmoBundle::security/successlogin.html.twig')
                    ), 400);
            }
            else
            {
                $errors = $this->get('validator')->validate($form);

                $parametersArray['result'] = new JsonResponse(
                    array(
                        'message' => 'Failure! User not registered!',
                        'result'  => $this->renderView('ImmoBundle::security/successlogin.html.twig'),
                        'errors'  => $errors,
                    ), 200);
            }
        }

        $parametersArray['register_form'] = $form;
        $parametersArray['errors'] = $errors;

        return $parametersArray;
    }

然后我创建了一个主控制器,其中正在加载注册表单:

    /*
     * @Route("/", name="MainPageNotPaginated")
     */
    public function indexAction(Request $request)
    {
        /**
         * Load register form
         */
        $registerForm = $this->get('register_form_service');
        $registerFormParameters = $registerForm->loadRegisterForm($request);

        return $this->render(
            'ImmoBundle::Pages/mainPage.html.twig',
            array(
                'register_form'  => $registerFormParameters['register_form']->createView(),
                'errors'         => $registerFormParameters['errors'],
                'result'         => $registerFormParameters['result'],
                )
        );
    }

此外,我已经在我的javascript文件中添加了一个ajax调用:

$('.registerFormContainer').on('submit', '.ajaxRegisterForm', function (e) {
        e.preventDefault();

        $.ajax({
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                data: $(this).serialize()
            })
            .done(function (data) {
                if (typeof data.message !== 'undefined') {
                    $('.registerFormContainer').html(data.result);
                }
                alert('success');
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                if (typeof jqXHR.responseJSON !== 'undefined') {
                    $('.registerFormError').html(jqXHR.responseJSON.result);
                } else {
                    alert("fail");
                }
            });
    });

现在,当我提交注册表而没有填写数据(通常应该返回错误)时,我已经取得了成功'警报。同样的成功'提交的注册表格有效时,警报可见。

我已经尝试了

  

的console.log(data.message)

但是控制台说' undefined'。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

好的,我已经弄明白了。我刚刚将这一行添加到我的主控制器(而不是服务器):

if ( $request->isXmlHttpRequest() ) {
    return $registerFormParameters['result'];
}