Home  >  Q&A  >  body text

Ionic Angular HTTP POST request PHP

I'm trying to use HttpClient in Angular to perform a basic POST request from my ionic Angular app. From that POST, I need to pass the payload to a PHP file so that I can manipulate another function in PHP.

I seem to be able to echo the entire data, but trying to get a single value gets an error.

The following is my code under home.ts

test() {
    let data = {
      firstname: "John",
      lastname: "Wick"
    }

    const headers = new HttpHeaders();
    headers.set('Content-Type', 'application/json; charset=UTF-8');
    headers.set('Access-Control-Allow-Origin', '*');
    headers.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');

    this.http.post(this.php_url, data, {headers: headers}).subscribe((res) => {
      console.log("Posted successfully")
      console.log(res);
    }, (err) => {
      console.log(err.error);
    });
  }

In my index.php file I have the following code.

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: *');
    header('Content-Type: application/json');

    $json = file_get_contents('php://input');

    echo $json->firstname;
?>

I am able to echo $json, but not when trying to get a single value. How to get a single value from JSON data?

P粉846294303P粉846294303379 days ago618

reply all(1)I'll reply

  • P粉715304239

    P粉7153042392023-09-09 20:54:38

    You must use

    print_r($json['firstname']);

    Installed

    echo $json->firstname;

    reply
    0
  • Cancelreply