Home » Php » javascript – AJAX form submission – No data returned

javascript – AJAX form submission – No data returned

Posted by: admin July 12, 2020 Leave a comment

Questions:

Form:

<form action="" id="register" method="post">
    <input type="text" placeholder="eg. John">
    <input type="text" placeholder="eg. Appleseed">
    <input type="text" placeholder="[email protected]">
</form>

JS:

$('form#register').on('submit',function (e) {
    $.ajax({
        url: 'submit.php',
        cache: false,
        type: 'POST',
        context: this,
        data : $(this).serialize(),
        success: function(json) {
            console.log("json: " + json);
        }
    });
    e.preventDefault();
});

PHP:

$formData = json_encode($_POST);
echo print_r($formData,1);

… after filling the form and hitting submit, it does submit the form without an error, but the data returned (JSON) is empty:

json: []

What am I doing wrong?

How to&Answers:

This is because you are not using name attribute in your fields

serialize() 

Requires name field in your form

Answer:

1:-

$formData = json_encode($_POST);
echo print_r($formData,1);

should be :-

$formData = json_encode($_POST);
echo $formData;

2.You are not having name attribute in your form fields. please provide that otherwise serialize() will not work correctly.