How to make an AJAX request to php? (With JavaScript Vanilla)

0

I'm trying to make an AJAX request to a method in my Brands driver.

const filter = () => {
let data = {marca:"a"};
fetch("www.algoalgo.com/marcas/marcas/filtro",{
    method: "POST",
    body: JSON.stringify(data) ,
    headers: {
        "Content-Type": "application/json"
    }
}).then(response=>{
    return response.json();
}).then(data=>{
    console.log(data);
});
}

Here is the driver:

   public function filtro(){

    $marca = $_POST["marca"];
     //Aqui esta la llamada a el modelo,que busca en la base marcas que contengan "a".
    $data = $this->Productos->filtro($marca); 

    echo json_encode($data);
}

But in console I get the following error:

  A PHP Error was encountered      

Severity: Notice

     

Message: Undefined index: brand

How can I get it to run correctly?

    
asked by Ale 23.08.2018 в 17:11
source

1 answer

1

How far I can see the error is in the Content-Type, this may sound a bit ostentatious, but in true javascript vanilla, it is used is XMLHttpRequest, fetch is a wrapper with promises (or a new api that has nothing what to do with XMLHttpRequest, I still do not read about it). With XMLHttpRequest the way to send the data, the Content-Type, is

"Content-Type": "application/x-www-form-urlencoded"

which is the type of content sent as such by the basic forms in html, and from javascript the FormData was used to send the data, which is how I still do it, although I was asked to try the new api.

If you use that type of content, it is very likely that the request will be recognized by the server as variables to fill the superglobal $ _POST.

On the other hand, with

"Content-type": "application-json"

I guess the way to process that data is by extracting the "raw" string, and processing it with json_decode in php.

$json = file_get_contents('php://input');
$data = json_decode($json);

Which will take the information from the direct input flow of php, which is usually a text string and using the corresponding function or method can convert that text to json format, to the corresponding data type that can be process from the language of the shift.

    
answered by 23.08.2018 / 19:55
source