Having trouble sending data with a POST request using Angular 4's HttpClient?

Angular 4.4.4
This is an introduction to my app component

constructor(
    private http: HttpClient,
)

this.http.post('/api.php', {name, age}).subscribe(response => {
    console.log(response);
});

api.php    ->    exit(json_encode($_POST));

No data received in $_POST

Returning an empty array

(

let xmlRequest = new XMLHttpRequest();
.... is functioning properly)

I have attempted to set the header

  let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8');

but it does not seem to be working

I apologize for this issue as I have spent a full day trying to solve it.

ps. Both client and server are from the same origin.

Answer №1

One way to handle parameters on the Angular side is by using a FormData Object.

const params = new FormData();
params.append('param1', 'value1');
params.append('param2', 'value1');
this.http.post('/api.php', params).subscribe(....)

In your PHP project, you can access these parameters using $_POST['param1'] and $_POST['param2'].

The method of using FormData Object seems more straightforward to me compared to dealing with file_get_contents.

Answer №2

Feel free to give this a try, I believe it could be helpful for you

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';


@Injectable()
export class LandingService {

    private apiEndpoint = 'http://localhost:5000/';

  list:any;
  headers : any;
  constructor(private _http: HttpClient){
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
  }
     getSearchResults(searchText){
          this.list ={"sentences":searchText}
          return this._http.post(this.apiEndpoint+'searchBotsNew',this.list,this.headers)
          .map(response =>response.json())
          .do(data => console.log(JSON.stringify(data)));

      }



}

Answer №3

The solution to the problem has been discovered by me.

When dealing with PHP, it is important to note that $_POST will only accept formdata.

If you set the request header as 'Content-Type: application/json', you can then retrieve the data using

file_get_contents('php://input');

This means that:

$_POST = json_decode(file_get_contents('php://input'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using npm to install Angular Bootstrap, the versions that are installed do not always match the specific versions

Displayed below is the content of my package.json file. { "name": "MyProject", "private": true, "version": "0.0.0", "scripts": { "test": "karma start ClientApp/test/karma.conf.js" }, "devDependencies": { "@angular/animations": "5.0.2", "@angular/common": ...

Looking to eliminate the usage of hostname, username, and password in PHP code

Here is some PHP code I need help with: <?php /* $host='127.0.0.1'; $uname='root'; $pwd='password'; $db="android"; */ require_once('dbConnect.php'); /* $con = mysql_connect($host,$uname,$pwd) or die("connect ...

The service.subscribe function in Angular's Component Constructor is not functioning properly after the update

There are two components in my project, a parent and child component, and I am using a shared service to transfer data between them. The structure of the Service Class is as follows: export class AddItemDataTransferService { // Observable string sourc ...

Storing Angular 4 Http Post response data in an object

I'm currently working with Angular 4 in conjunction with an Asp.net web API. I am facing difficulties in reading the properties of my response. This is how my response appears: https://i.stack.imgur.com/NDJCo.png Here is my post request: postLogi ...

What is the most efficient method for checking the type of a key or value within a 'foreach' loop?

How can I verify the key and value of an array expression being iterated over in a foreach loop, such as: foreach ($reasons as AuthenticationResponse $reason) ... Is there a different approach to this other than using an instanceof check within the loop? ...

Using Angular to include more than two parameters in an HTTP GET request

Currently, I am developing an application that requires downloading a file upon clicking a button within a template. The screen displays multiple files, each with its own corresponding button. I need to send the index number of the array to Angular and pas ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...

Encountering a 403 error upon refreshing the page of my Angular 6 project

I am currently working on an Angular 6 project with JWT authorization deployed on AWS Elastic Beanstalk and utilizing CloudFront. I am using the @auth0/angular-jwt library to manage everything efficiently. The setup is functioning smoothly, and I have a li ...

Roles in the Nebular system always have the granted status set to true by default

Hey there, I'm currently setting up Nebular to handle roles. Everything is working fine on the server side, but on the front end side, accessControl.isGranted() always returns true regardless of the role. Here's a snippet of the code I have been ...

Retrieving Mysql field data from an array

I have a script designed to showcase files within a specific directory: <?PHP # Defining the current directory $directory = dir("./"); # Uncomment this line if you wish to activate Extension Filter: $allowed_ext = array(".deb", ".ext", ".ext", ".ext" ...

Is it feasible to obtain the userId or userInfo from the Firebase authentication API without requiring a login?

Is it feasible to retrieve the user id from Firebase authentication API "email/password method" without logging in? Imagine a function that takes an email as a parameter and returns the firebase userId. getId(email){ //this is just an example return t ...

How to Retrieve Data from an HTML Table using the Laravel Framework

I have a unique and interactive Dynamic Sortable Table where I can effortlessly add or delete rows likethis uploaded image here. There is an intriguing loop in my controller that runs precisely 4 times, based on the number of columns in the table. However, ...

Replicating the Angular project folder is not effective

Instructions for using Angular's quickstart script are as follows: git clone https://github.com/angular/quickstart.git quickstart cd quickstart npm install npm start If I follow these steps, everything works perfectly. However, if I duplicate this d ...

Leveraging Angular for Parsing JSON Data

I have a JSON object that I want to use in my code. The goal is to assign the values of certain properties from the JSON object to four variables in my Angular project. These variables are named as follows: authorText : string; titleText : string; duratio ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

``There seems to be an issue with clicking an element in selenium

Having trouble with selenium while testing an angular site. Need to click on the pub name field on this screen: https://i.stack.imgur.com/i2NEO.png The side menu is open and here is the HTML: https://i.stack.imgur.com/0AxR9.png Tried waiting for the ele ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Using the Zend HTTP library, Privoxy, Tor, and cURL work together seamlessly

Seeking expert assistance as I am confronted with a puzzling situation. Allow me to provide some context on what I am attempting and the current setup. Initially, I had a script that successfully posted over an https form using Zend_Http_Client. My server ...