I can't manage to send data in post from an ionic app to a php controller


#1

I can’t manage to send data in Post from an ionic2 app to a php controller.

It result always that what I am posting is ‘null’.
The controller is part of a symfony web app.
This is the ionic2 provider function that send data using Post:

createPost(post){
return new Promise((resolve, reject) => { 
  this.data_to_send = {post: post};
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  this.http.post(this.apiUrl+'/ion/create', JSON.stringify(this.data_to_send),  {headers: headers})
    .subscribe(res => {
      console.log(JSON.stringify(this.data_to_send));
      this.data_to_send = null;
      resolve(res);
    }, (err) => {
      console.log(JSON.stringify(this.data_to_send));
      this.data_to_send = null;
      reject(err);
    });
});

I followed a tutorial about API calls.
I basically copied it so it shouldn’t be here the catch.
While this is the controller php function that receives it:

public function postCreationAjaxIonAction(Request $request){
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    $request = $this->getRequest();
    if ( $request->isMethod('POST') ) {
        $post = $request->request->get('post', null);
        if($post == null){
            $data = array();
            $data['success'] = false;
            $data['message'] = "post is required";
            $data['dump'] = $request->request->all();
            $data_output_json = json_encode($data);
            $response = new Response(
                'Content',
                Response::HTTP_OK,
                array('content-type' => 'application/json')
            );
            /*$response->headers->set('Access-Control-Allow-Origin', "*");
            $response->headers->set("Access-Control-Allow-Methods", "POST, GET");
            $response->headers->set("Access-Control-Max-Age", "3600");
            $response->headers->set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");*/
            $response->setContent($data_output_json);
            $response->prepare($request);
            $response->send();
            die();
        }
        $author = $post['author'];
        $content = $post['content'];
        $category = $post['category'];
        $tags = $post['tags'];
        if($tags == null){
            $tags = array();
        }
        self:: createPostAction($author, $content, $category, $tags);
        $data = array();
        $data['success'] = true;
        $data['message'] = $author;
        $data_output_json = json_encode($data);
        $response = new Response(
            'Content',
            Response::HTTP_OK,
            array('content-type' => 'application/json')
        );
        /*$response->headers->set('Access-Control-Allow-Origin', "*");
        $response->headers->set("Access-Control-Allow-Methods", "POST, GET");
        $response->headers->set("Access-Control-Max-Age", "3600");
        $response->headers->set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");*/
        $response->setContent($data_output_json);
        $response->prepare($request);
        $response->send();
        die();
    }else {
        $data = array();
        $data['success'] = false;
        $data['message'] = "No post request submitted";
        $data_output_json = json_encode($data);
        $response = new Response(
            'Content',
            Response::HTTP_OK,
            array('content-type' => 'application/json')
        );
        $response->headers->set('Access-Control-Allow-Origin', "*");
        $response->headers->set("Access-Control-Allow-Methods", "POST, GET");
        $response->headers->set("Access-Control-Max-Age", "3600");
        $response->headers->set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        $response->setContent($data_output_json);
        $response->prepare($request);
        $response->send();
        die();
    }
}```
Please ignore the mere fact that this is a sort of frankenstein monster.

I am working on getting it cleaner.

The function is called corretly, I get the response back, but it says it always recives a null object.
I cannot figure why it happens.
I console out, in ionic, the data I am sending:

console.log(JSON.stringify(this.data_to_send));

and this is a possible result:

{"post":
    {"author":"author name",
    "content":"the contnet",
    "category":"3",
    "tags":["3","4"]
    }
}

so far everything seems fine

But in the php I stop on the first if clause

$post = $request->request->get('post', null);
        if($post == null){
            $data = array();
            $data['success'] = false;
            $data['message'] = "post is required";
            $data['dump'] = $request->request->all();

and this is the response I get:

{
      _body: "{"
      success ":false,"
      message ":"
      post is required ","
      dump ":[]}",
      status: 200,
      ok: true,
      statusText: "OK",
      headers: Headers…
    }

where dump":[] is the result of:

$data['dump'] = $request->request->all();

please help me, it makes no sense to me


#2

Find the source of the problem, don’t start debugging at the end:
You should look at the dev tools while sending the data to see if the Ionic app sends the correct data.

If you are testing on a real device:
Did you remote debug the problem on the device already?
Follow these instructions here to debug the problem in Safari dev tools:
https://ionic.zone/debug/remote-debug-your-app#ios
Follow these instructions here to debug the problem in Chrome dev tools:
https://ionic.zone/debug/remote-debug-your-app#android
Look at the console and network tabs for errors.

If not: Just hit F12.


#3

I checked the network tab but I forgot to mention it in the question:
This is the request payload:

 {
    "post":{
        "author":"foo",
        "content":"bar",
        "category":"2",
        "tags":["3","4"]
    }
}

as expected,

this is the request headers

POST /app_dev.php/blog/ion/create HTTP/1.1
Host: ghio-symfony-delfins.c9users.io
Connection: keep-alive
Content-Length: 80
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, /
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Content-Type: application/json
Referer: http://localhost:8100/?ionicplatform=android
Accept-Encoding: gzip, deflate
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4

still something is wrong, as this php line

$post = $request->request->get('post', null);

claims that $post is null


#4

I don’t know how $request->request->get() works, but the payload is a JSON string (?). You should debug the data in PHP and output or log $request and the methods you call on it.


#5

If I dump the $request i get this:

{
    "attributes":{},
    "request":{},
    "query":{},
    "server":{},
    "files":{},
    "cookies":{},
    "headers":{}
}