简体   繁体   中英

Can not send form to PHP script

I used some good ol' ajax for a submit function for a form I made. I made a little example with the same javascript I used. If the form was sent properly, then the user will not be alerted with anything. If the form was not sent, then the user will be alerted with "reee." In my case, the user is alerted with "reeeeee" as the form does not seem to be sent to the php script and I don't know why.

It goes a little likes this:

html

<form id = "theform" >
    <input name = "noodz" required>
</form>
js

const form = document.getElementById("theform");
form.addEventListener("submit", submitfunc);

function submitfunc(e) {

    e.preventDefault();
    const thing = new XMLHttpRequest();
    thing.open("POST", "upload.inc.php");

    thing.upload.addEventListener("progress", e => {
        console.log(e);

    });

    thing.onreadystatechange = function() {
        if (thing.readyState == 4 && thing.status == 200) {
            var message = thing.responseText;
            alert(message);
        }
    }

    thing.setRequestHeader("Content-Type", "multipart/form-data");
    thing.send(new FormData(form)); // <- where form is sent
}
php

<?php 
    if (isset($_POST['noodz'])){
        //form was sent

    } else {
        //form wasn't sent
        echo "reeeeeeeeeeeee"
    }
?>

You need to remove the line

thing.setRequestHeader("Content-Type", "multipart/form-data")

and let XHR set the content-type value itself correctly and generate the correct MIME boundary (if needed - which it isn't, for your simple form).

Here's a demo https://jsfiddle.net/oxaqfbcd/ - if you look in the browser's Network tool you'll see the request correctly formed with the form data detected.

If you add that line of code back in and run it again, you can contrast the appearance of the request body section with when the line is not there, to see what effect it has.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM