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

411
Visualizações
jQuery post fail callback does not display response for code 400

I have a following jQuery post request:

$.post("ajax.php", data).done(
    function(response){
        // do something when response is ok
     }
   ).fail(
    function(response){
          $("#error").html(response);
     }
 );

In my ajax.php file when something goes wrong I return HTTP response code 400 with a message:

header("HTTP/1.0 400 Error");
echo "Some error message";
exit();

When I check the response for faulty call in my browser I can see the status code Status Code:400 Bad Request and a response text I passed in error message. But the jQuery's .fail callback is not displaying my response.

How can I get the access to the fail/error response text?

EDIT

I tested my code and the .fail callback is being triggered, I just cannot get the response message being displayed.

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

0

You need to use jqXHR:

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

.fail is one the available Promise methods of the jqXHR object,

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

You can use the responseText property to get the error message as :

$.post("ajax.php", data).done(
    function(response){
        // do something when response is ok
     }
   ).fail(
    function(jqXHR, textStatus, errorThrown) {
          $("#error").html(jqXHR.responseText);
     }
 );

Reference : http://api.jquery.com/jquery.ajax/#jqXHR

over 4 years ago · Santiago Trujillo Relatório

0

I always use 500 for an ajax fail code and it usually gets picked up by .fail for me. JQ API for .post has a long list of nested links describing how they handle JqXHR object and how it interacts with JQ as a whole.

Since you're not triggering .fail with your status, you could have your success check for your specific status code in the .success or .done function like so.

//post stuff
.success(function(response){  
   if(response.status == 400){
      //error stuff
   }
});

The advantage of performing your own checks in .done or .success is that you can define some nifty behaviors for different statuses you'd like to return from your server. There are literally dozens of different ways to handle ajax returns and define callback behaviors.

**Here's another SO question that has some other resolutions.

jQuery AJAX Error Handling (HTTP Status Codes)

**The syntax here is slightly different because this question focused on the .ajax method instead of .post, but the ideas and resolutions proposed should still work.

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