How to upload the contents of a variable to the backend using javascript fetch?

Asked

Viewed 696 times

-4

I can’t replace ajax with fetch

I’m taking all libraries out of my code, and I’m trying to make the most of the resources pure javascript offers, like fetch. However, I am not able to make a request to my backend (PHP) and bring the result so that I can manipulate in frontend.

I am currently using jquery ajax

I am currently using ajax to perform this request, and it is working legal. I take the value of select in html, step by parameter in the function, and make a query in postgresql, this same returns a json of the query, and I return it to the frontend. Currently the code is like this:

    //AJAX QUE CONSULTA O BANCO E TRAZ O MOTORISTA DE ACORDO COM A FILIAL
 function buscarMotorista(idfilial) {
     $.ajax({
         url: '../documentosConsulta.php?acao=buscarmotorista',
         type: 'post',
         async: true,
         data: {
             idfilial
         },
         success: function(result) {
             //SEMPRE QUE FOR ARRAY EU PRECISO DAR UM JSON.PARSE PARA TORNAR LEGÍVEL PARA O JAVASCRIPT
             if (result) {
                 let json = JSON.parse(result)
                 listarMotorista(json)
             } else {
                 toastr.warning('Motorista não encontrado!', 'Atenção!')
                 motorista.innerHTML = ''
             }
         },
         error: function(result) {
             console.log(result)
             toastr.error('Contate o desenvolvedor!', 'Erro!')
         }
     })
 } 

Now I’ll put the request using fetch instead of ajax. The backend remains the same.

I tried to do the same using fetch and could not... The code is falling in the catch. It is giving code 500 Internal Server Error. I am forgetting something?

function buscarMotorista(idfilial) {
     fetch('../feriasConsulta.php?acao=buscarmotorista', {
         method: 'POST',
         body: idfilial
     }).then(response => {
         return response.json()
     }).then(dados => {
         dados.map((f) => {
             let lista = `
                <option value="${f.idmotorista}">${f.nome}</option>
            `
             motorista.innerHTML += lista
         })
     }).catch(erro => {
         console.log(erro)
         toastr.warning('Motorista não encontrado!', 'Atenção!')
         motorista.innerHTML = ''
     })
 }

2 answers

-1

If error 500 is occurring, then there was some problem with your backend, looking at the code, it may be that the "idfilial" did not reach it. Try to do so, if the problem persists, check what is coming in the backend:

const url = '../feriasConsulta.php?acao=buscarmotorista';
const dados = {
    idfilial: '123456'
};
const options = {
    method: 'POST',
    body: JSON.stringify(dados),
    headers: {
        'Content-Type': 'application/json'
    }
}

fetch(url, options)
    .then(res => res.json())
    .then(res => console.log(res));
    .catch(erro => {
         console.log(erro)
         toastr.warning('Motorista não encontrado!', 'Atenção!')
         motorista.innerHTML = ''
});

Here is a tutorial that explains better how to use fetch

https://attacomsian.com/blog/using-javascript-fetch-api-to-get-and-post-data

  • My backend is not getting the fetch post, when I give a var_dump($_POST) it returns NULL. I need to pass some more parameter in headers?

  • I tried to send by GET and it worked, I gave a var_dump($_GET) and it returned the content on . then(). I’m missing the fetch POST syntax, because the backend is ok...

-2


Solution:

For GET PHP was receiving normal, now by POST I needed to make the following changes:

function buscarMotorista(idfilial) {
     const data = 'idfilial=' + idfilial // Concatenar a chave

     fetch('../feriasConsulta.php?acao=buscarmotorista', {
         method: 'POST',
         body: data,
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded' // Informar o tipo
         }
     }).then(response => {
         return response.json()
     }).then(dados => {
         dados.map((f) => {
             let lista = `
                <option value="${f.idmotorista}">${f.nome}</option>
            `
             motorista.innerHTML += lista
         })
     }).catch(erro => {
         console.log(erro)
         motorista.innerHTML = ''
     })
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.