0

Why is my code not sending the data to server ? It does display the data into the console but doesn't seem to be sending anything.

document.querySelector("form").addEventListener("submit", function (e) {
            e.preventDefault();

            var formData = {
            "name": e.target.elements.name.value,
            "author": e.target.elements.author.value,
            "link": e.target.elements.link.value
            }

            var req = new XMLHttpRequest();

            req.open("POST", "http://localhost/javascript-web-srv/post_form.php", true);
            req.setRequestHeader("Content-Type", "application/json");

            req.send(formData);

            formData = JSON.stringify(formData);

            console.log(formData);

        });
7
  • 1
    req.send(JSON.stringify(formData)); Commented Aug 21, 2017 at 13:30
  • Why stringify? Why not just send the data? Commented Aug 21, 2017 at 13:37
  • @JeremyThille because you are sending an array Commented Aug 21, 2017 at 13:42
  • So? What's wrong with sending an array? Commented Aug 21, 2017 at 13:48
  • @query — formData is a plain object, not an array. Commented Aug 21, 2017 at 14:02

1 Answer 1

1
req.send(formData);
formData = JSON.stringify(formData);

Your code is backwards.

In order to send JSON, you need to convert your object to JSON and then send it.

formData = JSON.stringify(formData);
req.send(formData);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.