0

I am trying to build a small form in my website which will use ajax to save the form details to the database with php. I can do it with jquery, since I am a student, I don't want to use any external libraries. I was able to use ajax "get method" and even manage to create a post method but I have no idea how to receive this data in the php script and process it.

This is the ajax code i used to send json data

subForm.addEventListener('click',()=>{


  var forms = {
    "name": document.getElementById('name').value,
    "phone": document.getElementById('phone').value,
    "email": document.getElementById('email').value,
    "message": document.getElementById('message').value,
    "exe" : true
   }
   var jString = JSON.stringify(forms);
   var xhttp = new XMLHttpRequest();

   xhttp.open("POST", "recieve.php");
   xhttp.setRequestHeader("Content-Type" , "application/json")
   xhttp.send(jString);



});
  • so, after making the request, in your receive.php what $_POST consists? – G.Spirov Apr 19 '20 at 14:54
  • php doesn't understand json request bodies, meaning it won't be parsed by php automatically. You would need to read the raw input in order to get the text and ten parse it yourself – Patrick Evans Apr 19 '20 at 15:01

1 Answers1

-1

If you've managed to process a GET. You'll manage the POST just in the same way. By peeking in the global variable $_POST['myJson'] in your "recieve.php".

On the client side, you'd need then to stringify like so:

var jString = JSON.stringify({"myJson": forms});

Therefore, on the server side, $_POST['myJson'] will contain the object 'forms', which you constructed on the client side. And if you want to access let's say, the name property value, you do like so:

var nameValue = $_POST['myJson']['name'];
wiwi
  • 270
  • 2
  • 9
  • "If you've managed to process a GET. You'll manage the POST just in the same way." - not true. The data goes in different places and in different formats. – Quentin Apr 19 '20 at 15:06
  • "By peeking in the global variable $_POST['myJson'] in your "recieve.php"." — The code in the question will **not** populate `$_POST['myJson']`. – Quentin Apr 19 '20 at 15:06
  • "On the client-side, you'd need then to stringify like so" — There is no need and certainly no point to adding an additional layer of JSON stringification. – Quentin Apr 19 '20 at 15:07
  • Be helpful and bring on a correct answer – wiwi Apr 19 '20 at 15:09
  • I can't. The question is closed. There are perfectly good, correct answers on the duplicate question. – Quentin Apr 19 '20 at 15:10
  • Sorry, but the answer at which this is redirected is not answering the OP's question – wiwi Apr 19 '20 at 15:13
  • You're wrong, it does. – Quentin Apr 19 '20 at 15:14