Retreive Html form value in a PHP script using an Angular Service

时间:2018-06-04 16:50:38

标签: php angular angular-services

I have an Angular 5 App with a contact form and I want to be able to retreive data from this form via a service in my PHP Script.

Here is my html

contact.html

<div class="">
   <input [(ngModel)]= "subjet" name="subjet" type="text">
   <label for="">subject</label>
</div>

When I click on my from button I call a function sendmail(subject) in the same component.

contact.component.ts

export class ContactComponent implements OnInit {

constructor(private  sendMailService:SendMailService) { }

    sendmail(subjet):void{
         this.sendMailService.performGetEx().subscribe(  (v => 
         console.log('value: ', v)),
         (e => console.log('error: ', e)),
         (() => console.log('the sequence completed! :' ,subjet)));
    }

And finally my service :

Injectable()
export class SendMailService {

  private url = 'assets/php/sendmail.php'

 constructor(private http:HttpClient) { }
   performGetEx():Observable<any>{
     return this.http.get<any>(this.url,
     {
         responseType: 'text' as 'json'
     });
}

This service is the one that use the PHP Script but I can't find a way to retreive my subject value in my PHP Script.

When I do something like that $sujet = $_POST['sujet'];it doesn't work. It could have worked if my script was in the same folder as my contact component but it's not the case.

Do you know how I can do It ?

UPDATE 1 :

This link could be helpful, it might be the solution for people that have this issue : Angular HTTP post to PHP and undefined

Im my case when I do the following :

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$subject = $request->subject;

I have an error because my $postdata variable is empty ! Still don't know why

UPDATE 2 :

Like @Simos said I checked and I didn't see the data sent from Angular in my network.

So I changed my SendmailService class method from get to post.

Injectable()
export class SendMailService {

  private url = 'assets/php/sendmail.php'

 constructor(private http:HttpClient) { }
   performGetEx():Observable<any>{
     return this.http.post<any>(this.url,
     {
         responseType: 'text' as 'json'
     });
}

I get an other error HttpErrorResponse SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse.

I already had this error before and had to add the reponseType: 'text' as 'json' in order to avoid it...And now it don't work with the post method....

0 个答案:

没有答案