1

I need to load in the div id = "containerPosts" json text in symfony

In the directory web/app_dev.php/ajax the content is not seen json but if the div yes.

In the directory web/app_dev.php shows the error:

"The controller must return a response (null given). Did you forget to return a statement somewhere in your controller?"

Any idea to resolve the issue?

AppBundle\Controller\PostController.php

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
//use BackendBundle\Entity\Post;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class PostController extends Controller
{
    /**
     * @Route("/ajax")
     */
    public function indexAction()
    {
        return $this->render('AppBundle:Post:post.html.twig', array(

        ));
    }

    /** @Route("/ajax/posts", name="ajax_posts")
     * @Method({"GET"})
     */
    public function postsAction(Request $request)
    {
        if($request->isXmlHttpRequest())
        {
            $encoders = array(new JsonEncoder());
            $normalizers = array(new ObjectNormalizer());
            echo "hola2";
            $serializer = new Serializer($normalizers, $encoders);

            $em = $this->getDoctrine()->getManager();
            $posts =  $em->getRepository('BackendBundle:Post')->findAll();
            $response = new JsonResponse();
            $response->setStatusCode(200);
            $response->setData(array(
                'response' => 'success',
                'posts' => $serializer->serialize($posts, 'json')
            ));

            return $response;
        }
        echo "hola";
    }
}

AppBundle\Resources\config\Post.yml (Routes)

ajax_posts:
    path: /ajax/posts
    defaults: { _controller: AppBundle:Post:posts }

ajax:
    path: /ajax
    defaults: { _controller: AppBundle:Post:index }

AppBundle\Resources\views\Post\post.html.twig

{% block title %}AppBundle:Post:index{% endblock %}

{% block body %}
<h1>Welcome to the Ajax:index page</h1>
    <div id="containerPosts"></div>
{% endblock %}

{% block javascripts %}
    <script src="{{ asset("assets/js/jquery.min.js") }}"></script>
    <script>
        jQuery(document).ready(function($)
        {
            $.ajax({
                method: "GET",
                url: "{{ url('ajax_posts') }}",
                dataType: 'json',
                success: function(data)
                {
                    if(data.hasOwnProperty("response") && data.response === "success")
                    {
                        if(data.hasOwnProperty("posts"))
                        {
                            //http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try/3710226
                            if (/^[\],:{}\s]*$/.test(data.posts.replace(/\\["\\\/bfnrtu]/g, '@').
                                    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
                                    replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
                            {
                                var posts = JSON.parse(data.posts);
                                if(posts.length > 0)
                                {
                                    alert("aqui");
                                    var html = "";
                                    for(d in posts)
                                    {
                                        html += "<p>" + JSON.stringify(posts[d]) + "</p>";
                                    }
                                    $("#containerPosts").append(html);
                                }
                            }
                            else
                            {
                                console.log("INVALID JSON STRING");
                            }
                        }
                        else
                        {
                            console.log("POSTS NOT FOUND");
                        }
                    }
                },
                error: function(jqXHR, exception)
                {
                    if(jqXHR.status === 405)
                    {
                        console.error("METHOD NOT ALLOWED!");
                    }
                }
            });
        });
    </script>
{% endblock %}

BackendBundle\Entity

<?php

namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

/**
 * Post
 */
class Post
{
    /**
     * @var int
     */

    private $id;

    /**
     * @var title
     */
    private $title;

    /**
     * @var body
     */
    private $body;


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Post
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set body
     *
     * @param string $body
     *
     * @return Post
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    /**
     * Get body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }
}

BackendBundle\Resources\config\doctrine\Post.orm.yml

BackendBundle\Entity\Post:
    type: entity
    table: post
    id:
        id:
            type: integer
            nullable: false
            options:
                unsigned: false
            id: true
            generator:
                strategy: IDENTITY
    fields:
        title:
            type: string
            nullable: true
            length: 100
            options:
                fixed: false
        body:
            type: text
            nullable: true
Manply
  • 75
  • 1
  • 9

2 Answers2

1

I suspect because your return statement is inside an if statement. Can you try this instead:

public function postsAction(Request $request)
{
    $response = new JsonResponse();

    if($request->isXmlHttpRequest())
    {
        $encoders = array(new JsonEncoder());
        $normalizers = array(new ObjectNormalizer());
        echo "hola2";
        $serializer = new Serializer($normalizers, $encoders);

        $em = $this->getDoctrine()->getManager();
        $posts =  $em->getRepository('BackendBundle:Post')->findAll();
        $response->setStatusCode(200);
        $response->setData(array(
            'response' => 'success',
            'posts' => $serializer->serialize($posts, 'json')
        ));
    }

    return $response;
}

I'm not sure if it will fix the problem, but please try it.

Alvin Bunk
  • 7,621
  • 3
  • 29
  • 45
  • I have modified the code and I have put the following one, and it works perfectly. Thank you very much – Manply Mar 08 '17 at 16:07
0

I have modified the code and I have put the following one, and it works perfectly. Thank you very much

    $response = new Response();

    $encoders = array(new JsonEncoder());

    $normalizers = array(new ObjectNormalizer());

    $serializer = new Serializer($normalizers, $encoders);

    $EntityManager = $this->getDoctrine()->getManager();
    $client  = $EntityManager->createQuery("********")->getResult();

    $response->setContent(json_encode(array(
        'client' => $serializer->serialize($client, 'json'),
    )));

    $response->headers->set('Content-Type', 'application/json');
    return $response;
Manply
  • 75
  • 1
  • 9