Brian Moreno
Brian Moreno

Reputation: 1027

Send Params With Axios - VueJS

so I'm working with Axios in VueJS to send ajax requests. However I'm getting a bit of a problem when trying to send requests.

This is my JS code:

axios.post('http://localhost/app/php/search.php', {
    query: this.search //this should send the 'query' param
}).then(response => {
    this.variable = response.data
}).catch(e => {
    this.errors.push(e)
})

And this is the search.phpfile:

<?php

    require '../Functions.php';
    $obj = new Functions();

    $array = $obj->search($_POST['query']);

    echo json_encode(array_values($array));
?>

And I'm getting the following error on the PHP side: Notice: Undefined index: query in /path/to/app/search.php on line 6

Any reason as to why this is happening? Any help is greatly appreciated.

Update

this.search is a variable I have inside my data object:

data () {
    return {
      search: ''
    }
  }

This variable is binded to a textfield:

<input type="text" v-model="search" @keyup.enter="search()" />

And this inside my search() method is my axios request.

Upvotes: 1

Views: 1866

Answers (1)

Brian Moreno
Brian Moreno

Reputation: 1027

Ok so I was looking at a similar problem in Angular and it turns out Axios was sending the query param. However, in the php file I had to populate the POST variable with the JSON coming in from Axios. This is how I got it working:

<?php

    require '../Functions.php';
    $obj = new Functions();

    //Populate POST variable with incoming JSON from Axios.
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)):
        $_POST = (array) json_decode(file_get_contents('php://input'), true);
    endif;

    $array = $obj->search($_POST['query']);

    echo json_encode(array_values($array));
?>

Upvotes: 2

Related Questions