Symfony 2 FOS User Bundle Bootstrap modal AJAX Login

爷,独闯天下 提交于 2019-12-03 06:07:27
Valentin

I have found the solution. Here is what I added to my javascript,

<script>
    $(document).ready(function(){
        $('#_submit').click(function(e){
            e.preventDefault();
            $.ajax({
                type        : $('form').attr( 'method' ),
                url         : '{{ path("fos_user_security_check") }}',
                data        : $('form').serialize(),
                dataType    : "json",
                success     : function(data, status, object) {
                    if(data.error) $('.error').html(data.message);
                },
                error: function(data, status, object){
                    console.log(data.message);
                }
            });
        });
    });
</script>

And here is my onAuthenticationFailure method from my handler,

public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
    $result = array(
        'success' => false, 
        'function' => 'onAuthenticationFailure', 
        'error' => true, 
        'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
    );
    $response = new Response(json_encode($result));
    $response->headers->set('Content-Type', 'application/json');

    return $response;
}

I think that it was the URL from my Ajax method that was wrong. Thank you for your advices.

Andy Rosslau

I guess what youre looking for is this: Symfony2 ajax login.

your javascript would look sth. like this:

$('#_submit').click(function(e){
        e.preventDefault();
        $.ajax({
            type        : $('form').attr( 'method' ),
            url         : $('form').attr( 'action' ),
            data        : $('form').serialize(),
            success     : function(data, status, object) {
                if (data.sucess == false) {
                    $('.modal-body').prepend('<div />').html(data.message);
                } else {
                    window.location.href = data.targetUrl;
                }
            }
    });

You also have to modify the isXmlHttpRequest-part of your onAuthenticationSuccess-Method:

[...]
if ($request->isXmlHttpRequest()) {
            $targetUrl = $request->getSession()->get('_security.target_path');
            $result = array('success' => true, 'targetUrl' => targetUrl );
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
[...]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!