Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Controller should return response

Tags:

ajax

php

symfony

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?

like image 898
Tigran Avatar asked Mar 23 '26 04:03

Tigran


1 Answers

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

return new Response('success');
like image 59
Hubert Lcorche Avatar answered Mar 25 '26 19:03

Hubert Lcorche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!