0

I am using symfony3:

I am calling a method via ajax call:

Controller

/**
     * @Route("personnel/domainlist/{id}", name="ajax_method")
     * @Method("GET")
     */
    public function domainlist(Request $request,$id){
       $repository = $this->getDoctrine()->getRepository('AppBundle:ENTITYNAME');          
       $res=$repository->findBy(array('COLNAME' => $id));          
      // create a JSON-response with a 200 status code

      $response = new Response(json_encode($res));    
      $response->headers->set('Content-Type', 'application/json');
      return $response;
      die;
    }

form above code i am getting following result: print_r($res);

Array
(
    [0] => AppBundle\Entity\ENTITYNAME Object
        (
            [domain_id:AppBundle\Entity\ENTITYNAME:private] => 15
            [domain_title:protected] => ABC
            [domain_group_id:protected] => 1
        )
)

AJax code:

 $.ajax({
        url: "domainlist/" + pdoamin_id,      
        type: 'POST',
        dataType: 'json',        
         success: function(result) {
            alert(result);
             }
          });

  });

Anyone can help me how can i return json to ajax method in symfony3

3 Answers 3

1

You have to serialize your answer before push it to Response. There are two ways to do it (at least I know just two ways)

  1. The Serializer Component
  2. Implement interface \JsonSerializable (PHP version >=5.4 )

In both variants your json_encode function will be work as you expect.

I prefer second way for For its simplicity

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure if Symfony 3 has the class, but in Symfony 4, you can use the JsonResponse class.

import the class into your controller

use Symfony\Component\HttpFoundation\JsonResponse;

Then use one of its constructors in your return statement:

return new JsonResponse($dataToReturn);

That worked for me.

Comments

0
$repository = $this->getDoctrine()->getRepository('AppBundle:ENTITYNAME');          
       $res=$repository->findBy(array('COL_NAME' => $id));          
       $normalizer = new ObjectNormalizer();      
       $encoder = new JsonEncoder();
       $serializer = new Serializer(array($normalizer), array($encoder));
       $response=$serializer->serialize($res, 'json'); 

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.