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;
class RegistrationListener implements EventSubscriberInterface
{
private $router;
public function __construct(RequestStack $RequestStack)
{
$this->requestStack = $RequestStack;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess'
);
}
public function onRegistrationSuccess()
{
$request = $this->requestStack->getCurrentRequest();
if ($request->isXmlHttpRequest()) {
$array = array( 'success' => true );
$response = new Response( json_encode( $array ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
}
else{
$array = array( 'success' => false );
$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:
$.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?