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

200
Visualizações
Return json response in ajax request laravel

I have the following ajax code in my frontend.

var formData = $('#application-information-step-one').serialize();
var actionUrl = $('#application-information-step-one').attr('action');
$.ajax({
      url: actionUrl,
      type: 'POST',
      data: formData,
      success: function(data) {
        var resp = JSON.stringify(data);
        console.log(resp);
      },
      error: function(data) {

      }

And following code to return json response from my controller if the request is ajax:

        if ($request->ajax()) {
            return response()->json([
                'message' => 'Information saved sucessfully !'
            ],200)->headers('Content-Type', 'application/json');
        }

But with the above code setup. Laravel returns HTML code of same page from where the request was made.

HTML page is rendered in preview section of network tab .

Can anyone suggest what am I missing here ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Return JSON response from controller

if ($request->ajax()) {
    return response()->json([
        'status' => 'success', 
        'data' =>[], 
        'message' => 'Information saved successfully!'
    ], 200);
}

In AJAX success function code:

 success: function (data) {
     console.log(data.message);
 },

and add to AJAX request object next parameters too

dataType: 'json',
contentType: false,
processData: false
about 4 years ago · Juan Pablo Isaza Relatório

0

Check for Ajax request is incorrect, otherwise the controller wouldn't have outputted HTML.

You can try several things:

  • use Illuminate\Support\Facades\Request; at the top of the file
  • replace request->ajax() with Request::wantsJson()
  • use request()->ajax()

Any of the above subject to your Laravel version.

More details here

about 4 years ago · Juan Pablo Isaza 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