-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 = ''
     })
 }
						
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?
– Matheus Ricardo Brunelli
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...
– Matheus Ricardo Brunelli