Shri
Shri

Reputation: 752

PHP does not execute function called via Axios in Vue.JS

I am trying to write a Vue.JS module to do some data processing and send variables to a PHP functions in a seperate file. I'm using Axios to parse parameters to PHP. Now the problem is, the Axios request reaches the PHP file, but the PHP doesn't actually call the function that was intented to call.

PHP call from Vue app:

axios.post('./crmFunctions.php',{ params: { function2call:"sendQuery", id:1, mid:1, message: "Hello there!", event:"Query" }})
.then(response => this.responseData = response.data)
.catch(error => {});

PHP interpretation code:

if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
    if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }{
    $function2call = $_POST['function2call'];

    switch($function2call) {

    case 'sendQuery' : sendQuery($_POST['arguments'][0],$_POST['arguments'][1],$_POST['arguments'][2],$_POST['arguments'][3]);
    break;
    case 'other' : // do something;break;
        // other cases
    }
}
}

Where am I going wrong with this code? I managed to call the same function on AJAX previously.

Upvotes: 1

Views: 475

Answers (1)

arkuuu
arkuuu

Reputation: 648

The data that is send with axios is not put into PHP's $_POST. Instead, it is in the request body and most likely in json format. To get it, try the following code:

function getRequestDataBody()
{
    $body = file_get_contents('php://input');

    if (empty($body)) {
        return [];
    }

    // Parse json body and notify when error occurs
    $data = json_decode($body, true);
    if (json_last_error()) {
        trigger_error(json_last_error_msg());
        return [];
    }

    return $data;
}


$data = getRequestDataBody();
var_dump($data)

Upvotes: 1

Related Questions