3

I am having some problems with symfony controller why sending ajax request.

This is my controller

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Follow;
use AppBundle\Exception\FollowException;

class FollowController extends Controller
{ 
    public function ajaxAction(Request $request)
    {
    $authChecker = $this->get('security.authorization_checker');

    if(!$authChecker->isGranted('ROLE_USER')) {
        echo 'Access Denied';
    }

    $userId = $request->request->get('id');;

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

    $followedUser = $em->getRepository('AppBundle:User')->find($userId);

    if(!$followedUser) {
        echo 'User not exist';
    }

    $follow = new Follow();
    $follow->setUserId($followedUser->getId());
    $follow->setFollowerId($user->getId());

    $em->persist($follow);
    $em->flush();

    echo 'Success';

    return true;
    }
}

This is my simple ajax request

$('#subscribe-button').click(function() {
                $.ajax({
                    type: 'POST',
                    url: '/web/app_dev.php/follow',
                    data: 'id={{ user.getId }}',
                    success: function(data){
                      alert(data);
                    }
                });
            });

I don't want to return some template, that why i just return true, but I'm getting next in my alert.

Success! Controller must return response (true given) and html code of that page. How should I do it right?

1
  • Emphasis on: Controller must return response Commented Oct 29, 2015 at 18:48

1 Answer 1

7

Don't use echo in controller but return a Response object instead:

return new Response('success');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.