Gideon Appoh
Gideon Appoh

Reputation: 663

How to change form request format to json format

I have an application built on Yii 1.1. I'm having problems with the backend API. Here is the case.

I am new to API building and I have been tasked to build the backend API of a project. Now when it comes to Form submission from the frontend, my Tech Lead says I should change the form request format to JSON. Which I don't have any idea of. I tried to use file_gets_content('php://input') and json_decode in the codes below, but still not working.

        if (isset($_POST['TblTemplate'])) {
        //getting raw input of request
        var_dump($request = file_get_contents('php://input'));

        //decoding the JSON
        var_dump($input = json_decode($request, true));

        //passing input fields to model attributes
        $model->attributes = $input;

        //validating input fields (getErrors)
        if (!$model->validate()) {
            echo json_encode($model->getErrors());
        } else {
            //inserting (creating) template
            if(!$model->save()) {
                echo json_encode(['error' => 'Could not create template']);
            } else {
                echo json_encode(['success' => true]);
                exit();
            }
        }
    } else {
        $this->render('create',array(
            'model'=>$model,
        ));
    }

When I submit the form it gives me fields are empty. I'm very new to this API stuffs please help. Also when I run var dump or request it outputs this

string(156) "TblTemplate%5Bname%5D=Standard+Feedback+Request&TblTemplate%5Bemail%5D=gideon.a%40scopicsoftware.com&TblTemplate%5Bcontent%5D=I+am+a+new+template&yt0=Create" 

But vardump on input returns null.

Upvotes: 1

Views: 555

Answers (1)

Raphioly-San
Raphioly-San

Reputation: 404

Trying to give you a head start:

//getting raw input of request
$request = file_get_contents('php://input');

$json = json_decode($request);

if ($json !== null) {
    .... code ...
} else {
    $this->render('create',array(
        'model'=>$model,
    ));
}

Hope it helps

Upvotes: 1

Related Questions