-2

How would one normally go about sending a form from within a ReactJS single page application? I would normally just use POST and send it via php, but now that I am using a single page application I am not quite sure how I could accomplish the same thing. I just want to send a simple email with the contents of that form, that's it.

I have a shared hosting account with php, so i would like to use that and not buy a nodejs server on top of that.

A general, common approach would suffice as an answer.

George Welder
  • 3,787
  • 11
  • 39
  • 75

2 Answers2

1

You can do the exact same thing, craft a POST-Request inside your Javascript and proceed as usual.

fetch("/email", {
  method: "POST",
  body: form  //just pass the instance
})

Fetch-API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

You would need to have a clickhandler on your form-submit button, which would send the form to your PHP email-service via fetch.

xDreamCoding
  • 1,654
  • 1
  • 12
  • 18
  • Thanks a lot! I am not sure I understand though. Could you explain a little bit more what I would need to do. Will I need a 3rd party library for this? What is `fetch("/email")` doing here? – George Welder Oct 06 '17 at 14:40
  • 2
    No, `fetch` is the new Javascript Ajax API. – JulienD Oct 06 '17 at 14:41
1

You have to separate your application to two parts: Backend and Frontend. Your backend should be a REST Full API service and the frontend is your React app. Then you have to call the backend's endpoints from the React with a library like axios.

Read more:

What exactly is RESTful programming?

https://www.sitepoint.com/best-practices-rest-api-scratch-introduction/

https://github.com/mzabriskie/axios

Mhe
  • 39
  • 1
  • 7