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

194
Vistas
Javascript use fetch to get html response

I'm currently using ajax in a javascript file to get a response which is just some HTML.

My ajax script looks like :

$.ajax({
                    type: $form.getAttribute('action'),
                    method: $form.getAttribute('method'),
                    url: '{{ url|raw }}',
                    data: data,
                    success: function (html) {
                        html = new DOMParser().parseFromString(html, "text/html");
                        document.querySelector('#S3Adapter_storageClass').parentElement.replaceWith(html.querySelector('#S3Adapter_storageClass').parentElement);
                    }
                });

Basically it makes an ajax request to my controller which will return HTML content to me, in which I will just take a part to replace the current content of my page.

This works fine, but I'd like to skip jQuery and therefore use fetch() instead.

Except I can't. While searching the internet, I found on this site a way to do it: https://gomakethings.com/getting-html-with-fetch-in-vanilla-js/

So I did :

fetch('{{ url|raw }}', {
                    method: $form.getAttribute('method'),
                    body: data,
                }).then(function (response) {
                    // The API call was successful!
                    return response.text();
                }).then(function (html) {
                    // This is the HTML from our response as a text string
                    html = new DOMParser().parseFromString(html, "text/html");
                    document.querySelector('#S3Adapter_storageClass').parentElement.replaceWith(html.querySelector('#S3Adapter_storageClass').parentElement);
                }).catch(function (err) {
                    // There was an error
                    console.warn('Something went wrong.', err);
                });

Eventually, I do get some HTML content, but I feel like it's not the one that should be returned by the response like I did in Ajax. Instead, I just get the HTML of my current page. Is there something I did wrong?

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