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

162
Vistas
Javasript fetch doesnt work on PHP return when $.ajax works

I need to simply retrive data from server trought POST request. I can only edit front-end code. I found out that that jQuery function $.Ajax works and vanila javasript function fetch() doesn't. I figured it out that its due to PHP code doesn't echo message that i want to read but just returns it like this:

<?php 
    //some php logic
    return array(
        'result' => 'OK',
        'message' => 'data I shall receive',
    );
?>

Ajax request returns {result: 'OK', message: 'data I shall receive'} with following code:

this.sendFileToServer = async (file) =>{
    let data = new FormData()
    data.append('file', file);
    let uploadUrl = this.element.getAttribute('data-uploadurl');
    $.ajax({
        url: uploadUrl,
        body:data,
        success: function (msg){
            console.log(msg);
        }
    })
}

Javascript fetch request returns error 500 with following code:

this.sendFileToServer = async (file) =>{
    let data = new FormData()
    data.append('file', file);
    let uploadUrl = this.element.getAttribute('data-uploadurl');
    const response = await fetch(uploadUrl, {
        method: 'POST',
        body: data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(response => {
        console.log(response.text()); //I tried here return diffrent data like response.json(), but it doesn't work
    });
}

I know i could use Ajax function when it works, but i want my code to be jQuery free. I don't understand why the fetch function doesn't work when it should be the same request. Any help how to make it work or Explanation why i can't work would be nice.

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