How to send form data to a backend server?

I have a very simple view file with two field (Name and Address) and a submit button:

<? $form = ActiveForm::begin() ?>
<?= $form->field($model, 'name')->textInput() ?>
<?= $form->field($model, 'address')->textInput() ?>
<div class="form-group">
    <?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<? ActiveForm::end() ?>

I need to send the form data to a backend server with a different IP address .
Should I use Ajax?

Hi @robysottini

I’d rather call the backend model’s method in the frontend action in this case.

But, “different IP address”? Are the frontend and the backend on the physically different servers?

Yes. They are physically in different servers.

I’m not familiar with REST APIs, so I hope some expert will correct me if I’m wrong.

I would call REST APIs of the backend server in the frontend controller after it has successfully received the form submission. It will call some backend REST API instead of saving the data to the frontend db.

I’ll use http client in this case, it will be like this

if ($model->load(Yii::$app->request->post()) {
    // sent to API Server
    $client = new yii\httpclient\Client;();
    $response = $client->createRequest()
        ->setMethod('POST')
        ->setUrl('http://example.com/api/1.0/users')
        ->setData(['name' => $model->name, 'address' => $model->address])
        ->send();
    if ($response->isOk) {
        // redirect or anything else
    }
}
2 Likes