I do not receive the data sent from javascript (fetch) to php

0

I try to do a mini project to practice the use of the fetch (), the idea is to make a search engine which consists of typing a data in an input, when typing it will show information that contains part of that data entered. The thing is that I have an error, the data is not coming to the php. and send this error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. If in the php I give a value to the variable "$ search" works perfectly sending the results but of course I would not be doing anything .... the truth is not much php, I would like to know what I can do to receive the data. I would also like your opinion if I'm doing good practices in php and javascript.

JS

document.addEventListener('DOMContentLoaded', function 
 PrimeraFuncion() {
console.log("Hola desde el inicio del js")

const search = document.getElementById('text')
const card = document.getElementById("card")

search.addEventListener('keyup', e => {
    if(search.value){
        console.log(search.value)

            let searchword2 = search.value 
            let template = ''

        fetch('consult.php',{
            method: 'POST',
            body: searchword2
        })
        .then( response => response.json())
        .then(data => {
            console.log(data)
            console.log(data[0].NAME)
            template += '
            <li>
                ${data[0]}
            </li>
            '
            card.innerHTML = template
        })
        console.log(typeof(searchword2))
    }
})
})  

PHP

 <?php
 include_once("db.php");

$search = $_POST['search'];
if(!empty($search)){
    $query = "SELECT * FROM task WHERE NAME LIKE '$search%'";
    $result = mysqli_query($connection, $query);
    $json = [];
    while ($row = mysqli_fetch_array($result)) {
        $json[] = array(
            'ID' => $row['ID'],
            'NAME' => $row['NAME'],
            'DESCRIPTION' => $row['DESCRIPTION']
        );
    }
    $jsonstring = json_encode($json);
    echo $jsonstring;
}?>

HTML

<body>
    <input type="text" id="text" name="txt">
    <button type="submit" id="btn" >BUSCAR</button>

<div id="card">
    <!-- acà llegara la informaciòn -->
</div>

<script src="script.js"></script>

    
asked by Diego Guatibonza 29.09.2018 в 04:44
source

1 answer

1

The problem I see is that you are not sending the data correctly.

Try replacing:

let searchword2 = search.value 
let template = ''

fetch('consult.php',{
    method: 'POST',
    body: searchword2
})

By:

let searchword2 = search.value 
let template = ''
let body = new FormData();
body.append('search', searchword2);

fetch('consult.php',{
    method: 'POST',
    body: body
})
    
answered by 29.09.2018 / 05:27
source