FormData and Ajax Drawback – JavaScript – SitePoint Boards

This 12 months I’m going via jquery ajax issues I’ve by no means confronted earlier than. Each time I ship json by way of ajax $_POST is empty. I discovered a piece round the place the info is gathered from php://file like this:

$rawData = file_get_contents("php://enter");
$information = array();
parse_str($rawData, $information);
$returnMessage = array();

I’m unsure if I’m doing one thing mistaken in $ajax or if modifications had been made to JavaScript and PHP.

I’ve the identical subject with FormData. $_POST and $_FILES is empty. I’m unsure how one can work with the FormData from jquery ajax to finish file add scripts.

There must be two different hidden inputs with uploadUser and jobToken, each as tokens.

After I use the above methodology and dump $information variable I’ve this:

array(1) {
  ["------WebKitFormBoundary7IecehA7M07kVSFi
Content-Disposition:_form-data;_name"]=>
  string(123) ""upload_file[]"; filename="How To make piano melodies in FL Studio 20 Tutorial.mp4"
Content material-Kind: video/mp4

"
}

JS Code:

$("#uploadForm").on('submit', operate(e) {

    var tokenInserted = false;
    var fileToken = "";
    var currentFileIndex = 0;

    whereas (!tokenInserted) {

        var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".cut up("");
        var b = [];
        var size = 12;

        for (var i = 0; i < size; i++) {
            var j = (Math.random() * (a.size - 1)).toFixed(0);
            b[i] = a[j];
        }

        fileToken = b.be a part of("");

        if (fileStack.indexOf(fileToken) <= -1) {

            // insert the token
            fileStack.push(fileToken);
            currentFileIndex = fileStack.indexOf(fileToken);
            tokenInserted = true;

            // finish insert token

        }

        // finish add token to file stack
    }

    e.preventDefault();
    $.ajax({
        xhr: operate() {
            var xhr = new window.XMLHttpRequest();
            xhr.add.addEventListener("progress", operate(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = ((evt.loaded / evt.complete) * 100);
                    doc.querySelector("#uploadFileProgressBar" + fileStack[currentFileIndex]).setAttribute("worth", percentComplete);


                }
            }, false);
            return xhr;
        },
        kind: 'POST',
        url: '../php/scripts/upload_project_file.php',
        information: new FormData(this),
        dataType: 'json',
        contentType: 'software/json; charset=utf-8',
        cache: false,
        processData: false,
        beforeSend: operate() {
            // create the file add html and progress bar
            doc.querySelector("#projectFiles").innerHTML += "<div class="row g-2 align-items-center fileWrapper">" +
                "<div class="col-6 small"><span id="fileName" + fileStack[currentFileIndex] + "">Add file</span></div>" +
                "<div class="col-3 small text-end"><span id="fileSize" + fileStack[currentFileIndex] + ""></span></div>" +
                "<div id="uploadFileCol3Wrapper" + fileStack[currentFileIndex] + "" class="col-3 d-grid">" +
                "<progress id="uploadFileProgressBar" + fileStack[currentFileIndex] + "" worth="0" max="100" type="width:100%;"> 32% </progress>" +
                "</div>" +
                "</div>";


            // shut the add modal
        },
        error: operate() {

            doc.querySelector('#uploadFileCol3Wrapper' + fileStack[currentFileIndex]).innerHTML = "";
            doc.querySelector('#uploadFileCol3Wrapper' + fileStack[currentFileIndex]).innerHTML = "<p type="shade:#EA4335;">File add failed, please strive once more.</p>";

        },
        success: operate(information) {
            if (information.hasOwnProperty("message")) {

                change (information.message) {

                    case "success":
                        $('#uploadForm')[0].reset();
                        doc.querySelector("#uploadFileCol3Wrapper" + fileStack[currentFileIndex]).innerHTML = "";

                        doc.querySelector("#uploadFileCol3Wrapper" + fileStack[currentFileIndex]).innerHTML = "<div class="btn-group">" +
                            "<button class="btn btn-outline-secondary btn-sm dropdown-toggle" kind="button"" +
                            "data-bs-toggle="dropdown" aria-expanded="false">" +
                            "Actions" +
                            "</button>" +
                            "<ul class="dropdown-menu">" +
                            "<li><a category="dropdown-item" href="#">Motion</a></li>" +
                            "<li><a category="dropdown-item" href="#">One other motion</a></li>" +
                            "<li><a category="dropdown-item" href="#">One thing else right here</a></li>" +
                            "<li>" +
                            "<hr class="dropdown-divider">" +
                            "</li>" +
                            "<li><a category="dropdown-item" href="#">Separated hyperlink</a></li>" +
                            "</ul>" +
                            "</div>";
                        break;
                    case "error":
                        // deal with add file error
                        break;

                }

            }

        }
    });
});


effectively “kind” must be “methodology”, however thats simply semantics because it’s an alias.

In case you take a look at the payload within the Community tab of your browser, is it sending the info to PHP? (IE: Is the issue in PHP, or in your Javascript?)

underneath payload is request payload and it says this:

——WebKitFormBoundaryBHOh6RqABtwMcSjd
Content material-Disposition: form-data; title=“upload_file”; filename=“How To make piano melodies FROM SCRATCH FL Studio 20 Tutorial.mp4”
Content material-Kind: video/mp4

——WebKitFormBoundaryBHOh6RqABtwMcSjd
Content material-Disposition: form-data; title=“uploadUser”

df4d8ca3ba095a9bded14f9e2c307b6e
——WebKitFormBoundaryBHOh6RqABtwMcSjd
Content material-Disposition: form-data; title=“jobToken”

sdfsdfsdfsdf
——WebKitFormBoundaryBHOh6RqABtwMcSjd–

I solved this. Easy mistake. If anybody is dealing with this with FormData be sure $ajax has these settings: contentType: false,
processData: false,

Don’t be messing with the settings.



2 Likes

Source link

Add a Comment

Your email address will not be published. Required fields are marked *