Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

335
Visualizações
Symfony v2.8 Response( $message ) method 'returning' more than expected

My goal is to return a message to my web-page, where it is to be displayed, but instead of just the message, the value returned contains the message and html code for an error page!

Here is the Symfony bundle action routing and function definition:

/**
 * @Route("/Utilities/getMessages/{callSign}/{loginDateTime}",
 *        defaults={"callSign"="","loginDateTime"=""})
 *
 * @return:     json string.
 *
 */

public function getMessagesAction( $callSign, $loginDateTime ) { ... }

I am using the following code to return a message result to an ajax call:

Server-Side PHP code that is called by an Ajax call ...

$message = 'Some message to be displayed.';

// Return to the page and display the message ...

return new Response( $message );  // Inspecting $message shows only
                                  // 'Some message to be displayed.'

Client-Side JavaScript code that calls the above code and receives the response:

$.ajax( { // Send form data to the same page that the page came from
          type:        'POST',
          data:        data,
          cache:       false,
          async:       true,
          contentType: false,
          enctype:     'multipart/form-data',
          processData: false
        } )
.done( function( data, textStatus, jqXHR ) { ... } // Inspecting data
                                                    // shows more than
                                                    // 'Some ...
.fail( function( jqXHR, textStatus, errorThrown ) { ... }

When breakpoints are set at the return new Response( $message ); and first executable line in the .done(...) function, the PHP script execution gets to the breakpoint at the return new Response( $message ); statement without any errors and I can see that the parameter's value is 'Some message to be displayed.', as expected, but when paused at the .done() function's first line, the data parameter's value is: Some message to be 'displayed.<!DOCTYPE html><html>...</html>!

Where, if the html code is placed in a file and loaded into the browser it looks somewhat like this:

Whoops, looks like something went wrong.
1/1 FatalErrorException in debug-eval(1) : eval()'d code line 1:
Parse Error: syntax error, unexpected ')'
in debug-eval(1) : eval()'d code line 1

An obvious error message, but my code isn't using any eval() statements that could fail and the execution got to the Response statement without any errors. Is this a bug in the Symfony Response statement method/function? If not, how can I find out what is really happening, so I can fix it?

Follow-Up

Changing the server-side code to encode a json string and then decoding it on the client-side doesn't help.

Server-Side PHP code:

// Return to the login page and display the message ...

// $message'value => '{ "message":"' . $message . '"}';

$message = json_encode( [ 'message' => $message ] ); 
return new Response( $message );

Client-Side Javascript:

    ***unchaged***

In this case I'm still inspecting the data parameter, but it now now contain the json encoded message AND the html error page code. Feeding this to the JSON.parse( data ); statement to convert the json data to an javaScript object causes the javaScript to freeze. This isn't a json issue, the problem of the html code appended to the end of my message still is happening either way.

Thank you

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

It's not a very clear error message but it sounds like your error is coming from Xdebug, and not PHP.

You can see a similar issue here.

I would check your "Watches" tab in the PHPStorm debug tab, and also from PHPStorm go to Run > View Breakpoints and remove all of them. To be sure you could also deactivate XDebug temporarily (via php.ini settings) to confirm that the problem disappears.

over 4 years ago · Santiago Trujillo Relatório

0

Try returning a new JsonResponse($json) instead of new Response($json).

As in:

use Symfony\Component\HttpFoundation\JsonResponse;

// ...
return new JsonResponse(['message' => $message]);

If you really (and I mean really) want to return a Response for whatever reason, you can also do:

$response = new Response(json_encode(['message' => $message]);
$response->headers->set('Content-Type', 'application/json');

return $response;

Bear in mind that I have never tried the last alternative, because JsonResponse has always worked for me. Also, JsonResponse extends Response class, so if you need anything from Response class, you can get it in JsonResponse.

The last response example is attached to this answer because of this Symfony Documentation.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda