1

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.

Brian Moreno
  • 977
  • 4
  • 11
  • 39
  • Not sure about axios/vuejs, but see if this helps: https://stackoverflow.com/questions/13000386/post-array-empty-on-jquery-ajax-call . Maybe it's something similar. Same kind of thing with angular: https://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined – Don't Panic Sep 06 '17 at 19:17
  • Where is the post performed and what is `this.search` when it is? – Bert Sep 06 '17 at 19:20
  • I updated the post @Bert. – Brian Moreno Sep 06 '17 at 19:25
  • 1
    Well, it looks like you will send an object that looks like this `{query: "whatever search is"}` to search.php. So it seems right from the client side? – Bert Sep 06 '17 at 19:38
  • Yeah, i got it working now. Thanks anyway @Bert! :) – Brian Moreno Sep 06 '17 at 19:40

1 Answers1

2

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));
?>
Brian Moreno
  • 977
  • 4
  • 11
  • 39