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

149
Visualizações
How can I convert jQuery ajax to fetch?

This was my jQuery code before. Now I want to change it to fetch.

    function fetch(){
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });
}

I have changed the code to this now but I am getting bad request 400 status code

document.querySelector('#keyword').addEventListener('keyup',()=>{
    let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value
};
let url = "<?php echo admin_url('admin-ajax.php'); ?>";
fetch(url, {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
    .then((response) => response.text())
    .then((data) => {
        document.querySelector("#datafetch").innerHTML = data;
    })
    .catch((error) => {
        console.error('Error:', error);
    });
})

Am I missing something? It is from WordPress if this helps somehow.

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

0

  1. You forgot the pcat property in the data object
  2. jQuery, by default, sends form encoded data, not JSON encoded data. Use a URLSearchParams object instead of a string of JSON and omit the content-type header (the browser will add the correct one for you).
almost 4 years ago · Santiago Trujillo Relatório

0

In your jQuery code you defined data as

data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },

and in fetch you defined it as

let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value
};

so, you are not passing some value which was previously passed. No wonder that your server errors out. Let's change your code to

let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value,
    pcat: document.getElementById("cat").value
};

and try this out. If it still works, then you will need to find out what differs in the request and make sure that the request you are sending via fetch is equivalent to the request you formally sent via jQuery, then it should work well, assuming that the client-side worked previously with jQuery and the server-side properly handled the requests.

almost 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