Sf2: FOS UserBundle: AJAX registration

I am trying to register a user with AJAX.

I created an event listener on FOSUserEvents::REGISTRATION_SUCCESS

So, I'm trying to understand that an AJAX request has been made, but the answer on my client side does not satisfy me.

Here is my event listener, note that the response sent is a test, so of course there should not be an "else" condition.

<?php

namespace SE\AppBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Ajax listener on FOS UserBundle registration
 */
class RegistrationListener implements EventSubscriberInterface
{
    private $router;

    public function __construct(RequestStack $RequestStack)
    {
        $this->requestStack = $RequestStack;
    }

    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess'
        );
    }

    public function onRegistrationSuccess()
    {

        $request = $this->requestStack->getCurrentRequest();

        if ($request->isXmlHttpRequest()) {

            $array = array( 'success' => true ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;

        }
        else{
            $array = array( 'success' => false ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;
        }
    }
}

services.yml:

se.app.listener.registration:
    class: SE\AppBundle\EventListener\RegistrationListener
    arguments: ["@request_stack"]
    tags:
        - { name: kernel.event_subscriber }

JavaScript:

// Submit the request
$.ajax({
    type        : 'POST',
    url         : url,
    data        : data,
    success     : function(data, status, object) {

        console.log('success');
        console.log(data);

    },
    error: function(data, status, object){
        console.log('error');
        console.log(data);
    }
});

Firstly, it is strange that it goes into an error state.

console.log (data) returns the DOM of the successful registration page:

...
<p>Congrats brieuc.tribouillet7777@gmail.com, your account is now activated.</p> 
...

So, should this logic be here or should I redefine the controller? What am I doing wrong?

+4
source share
1 answer

- REGISTRATION_SUCCESS EventListener.

FormEvent .
:

class RegistrationListener implements EventSubscriberInterface
{
    // ...

    public function onRegistrationSuccess(FormEvent $event)
    {
        $request = $this->requestStack->getCurrentRequest();

        // Prepare your response
        if ($request->isXmlHttpRequest()) {
            $array = array( 'success' => true ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );
        } else {
            $array = array( 'success' => false ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );
        }

        // Send it
        $event->setResponse($response);
    }
}

.

. , .
, :

public static function getSubscribedEvents()
{
    return [
        FOSUserEvents::REGISTRATION_SUCCESS => [
            ['onRegistrationSuccess', -10],
        ],
    ];
}

. # 1799.

JsonResponse json_encode Content-Type.

, :

public function onRegistrationSuccess(FormEvent $event)
{
    $form = $event->getForm();

    if (count($validationErrors = $form->getErrors()) == 0) {
        return $event->setResponse(new JsonResponse(['success' => true]));
    }

    // There is some errors, prepare a failure response
    $body = [];

    // Add the errors in your response body
    foreach ($validationErrors as $error) {
        $body[] = [
            'property' => $error->getPropertyPath() // The field
            'message'  => $error->getMessage() // The error message
        ];
    }

    // Set the status to Bad Request in order to grab it in front (i.e $.ajax({ ...}).error(...))
    $response = new JsonResponse($body, 400); 
    $event->setResponse($response);
}

, .

+3

All Articles