I have created single page application using angular which contains contact form. for contact form i have used php mail function. I’m keeping that php file inside assets folder of angular project.
I am using angular HTTPCLIENT module to call that contact php file using below code in component:
this.http.sendEmail(user).subscribe( data => { let res:any = data; // debugger; console.log(`${user.name} is successfully booked appointment.`); this.elementRef.nativeElement.querySelector('.contact-form').innerHTML = "<div class='inner-content'><p class='success-msg'>Thanks for contacting us. We will contact you ASAP!</p>"; }, err => { console.log(err); this.loading = false; this.buttonText = "Submit"; },() => { this.loading = false; this.buttonText = "Submit"; } ); }
Service Code:
sendEmail(data: any) { return this.http.post(`../assets/inc/email.php`, data); }
I am trying to post the contact form. it’s not taking the php file. How to solve this issue please help me. Actually i am trying first time Anguar with Php. So please any help me to achieve this.
Advertisement
Answer
There are two issues that I see here:
- You cannot host
.php
files inside the assets folder of your Angular app unless your web server is set to serve php files. This may work if your server is someting like Apache, but it will not work with the angular dev server (ng serve
) — so this will never work locally. Instead you need to host the PHP files locally using something like xampp. this.http.post()
makes a request to a URL, not the path to the file in the project structure. Assuming you can get php files to work in the assets directory, the URL should look more like this:this.http.post('/assets/inc/email.php', data);
Be very careful about putting PHP files in the assets directory of your Angular app. This is not really how it is supposed to be used and there is a high risk that your PHP file contents (including emails, passwords, etc) will be exposed to the world if you try to host this Angular app on static web hosting like Github Pages, Firebase or Vercel.
I would recommend setting up a separate server for the PHP files and updating the http.post()
URL to call those files instead.