1

My javascript code:

function _(selector){ 
    return document.querySelector(selector); 
}

function submitForm(){
    var data = {
        name: _("#name").value,
        email: _("#email").value,
        message: _("#message").value
    }
    var output = JSON.stringify(data)
    var ajax = new XMLHttpRequest();
        ajax.open( "POST", "/PATH" );
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        ajax.onreadystatechange = function() {
            if(ajax.readyState == 4 && ajax.status == 200) {
                console.log('success')
            } else {
                console.log('fail')
            }

        }
        console.log(output)
        ajax.send(output);

}

When im trying do this with static data,it's work :

<?php
    $name = "mateusz";
    $to = "kaawkamateusz@gmail.com";
    $subject = "kucharz";
    $message = "message";
    mail($to, $subject, $message);
?>

but, on example :

$name = $_POST["name"];

doesn't work.

Im trying use JSON but again, idk how get value from AJAX form in PHP.

Im never use PHP before, need help :)

EDIT

print_r show :

Array
(
    [{"name":"asd","email":"asd@gmail_com","message":"12"}] => 
)
Mateusz Kawka
  • 422
  • 1
  • 4
  • 16

1 Answers1

0
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")

You say you are sending URL encoded form data …

var output = JSON.stringify(data)

… but your data is JSON encoded.


To URL form encode it use URLSearchParams.

var data = {
  name: "Example Name",
  email: "example@example.com",
  message: "This is a message"
}


var output = new URLSearchParams(data);
console.log(output.toString());

Note limited browser support. Consider using a polyfill.


Alternatively, set the correct content type for JSON and rewrite the PHP since JSON is not supported for $_POST.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335