Ionic Angular HTTP POST request PHP
P粉846294303
P粉846294303 2023-09-08 23:12:06
0
1
677

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粉846294303
P粉846294303

reply all(1)
P粉715304239

You must use

print_r($json['firstname']);

Installed

echo $json->firstname;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template