Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
jQuery and Express - success and error getting mixed up

This is sort of a basic question, but it's been nagging me for a while and I couldn't find any matching questions from my searches so far. So, apologies if it's too simple or repeated.

I have an API route (Express based) and I'm calling this route using jQuery AJAX call. Here is a simple stub to demonstrate the setup

$.ajax({
  url: "http://localhost:3000/admin/items/" + itemId,
  type: "POST",
  dataType: "json",
  data: itemData,
  contentType: "application/json",
  success: function(result){alert(result);},
  error: function(xhr, ajaxOptions, thrownError){
    alert("Could not update item details. Please try again later. Error: " + xhr.statusText);
  }
});

From the server, I confirmed that the status code returned is 200 and here is the implementation:

collection.update({ _id : mongo.ObjectID(req.params.id) }, req.body, function(err, result) {
  if(err){
    console.log("Error is: " + err);
    res.status(500).send("Could not update item with id: " + req.params.id);
  }else {
    if(result.result.n != 1){
     res.status(500).send("Could not find item with id: " + req.params.id);
    }
    else{
      console.log("Update successful");
      res.status(200).send("Successfully updated item id: " + req.params.id);
    }
  }
});

The functionality works perfectly, but at the end of the call, the error function is getting called and the alert I'm getting is: "Could not update item details. Please try again later. Error: OK".I tried a simple res.send without explicitly setting the status code too, but somehow it invariably calls the error function. What am I missing?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Further to my comment above, the reason this is occurring is because the dataType is set to expect a JSON response but express isn't sending JSON. When jQuery tries to parse the response it's unable to and throws an error even though the response status is 200.

If you wanted to keep the response you were sending in the initial example, simply removing the dataType from the ajax request would be enough, jQuery is normally pretty clever in figuring out what is being returned.

If however you wanted to receive JSON data (as clarified in the comments) then replace your response code with something like the following:

res.status(200).json({
  message: 'Successfully updated item',
  data: doc // document returned by mongo
});

Remember to change the error responses too to JSON. Even though jQuery would go to the error block anyway it's for the wrong reasons (invalid JSON rather then the error code) Something like this:

res.status(500).json({
  message: 'Server error occurred'
});
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda