3

How do I get the response from a PHP file in Angular 4?

If i place the PHP file in the assets folder, the GET request will find the file and it will download the content of the file. E.g

headers: Headers
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://localhost:4200/assets/php/test.php"
_body: "<?php ↵    echo 'response from php file';↵?>"

Also if I browse localhost:4200/assets/test.php it will donwload the php file to disk.

If I place the file in the same service folder and try to call it with ./test.php I get the 404 file not found error. I also get the 404 error if I try to target the file with the full path name like './app/services/test.php' (I've tried a few other variants aswell)

test.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

@Injectable()
export class TestService {

  data: any;

  constructor(private _http: Http) { }

  getTestData() {
    return this._http.get('assets/php/test.php') // <-- Here
      .subscribe(
      (res: Response) => {
        this.data = res;
        console.log(this.data)
      },
      (err: Error) => console.log(err)
      );
  }
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { TestService } from '../services/test.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  data: any;

  constructor(private _testService: TestService) {}

  ngOnInit() {
     this.data = this._testService.getTestData();
     console.log(this.data);
  }
}

test.php

<?php
   echo 'response from php file';
?>

app.moduel.ts

import { TestService } from './services/test.service';
...
providers: [TestService],

Project structure

enter image description here

1 Answer 1

2

I think that your PHP file must be handled by an Apache Server. PHP is interpreted by the server, not the client, that's why you get the source code of the script, not the results of this script. So, you have to call your PHP script as you do in your controller, but with an URL (or URI) that looks like :

https://someserver.tld/test.php

If "somserver.tld" runs a properly configured Apache PHP. You can try with any XAMP server on your local machine.

You have also to pass JSON headers and print JSON results to handle the results in your Angular Script.

Hope it helps

Sign up to request clarification or add additional context in comments.

1 Comment

I tried moving the file to an apache server and it worked like a charm. WAMP server --> http://localhost:8080/php/test.php - I also had to include the CORS header header("Access-Control-Allow-Origin: *");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.