0

I'm working on a small homemade CMS/portfolio-type thing, using HTML, PHP and Javascript (I'm trying not to use jQuery, or node.js), and I can't seem to make my FromData() object reach my php script...

I want to, when a form (used to create a new project page) is submitted, pass it through a small piece of js, and then send it to a php script that will write what needs to be written down in the database, create the files, etc...

In order to achieve this, I'm trying to use a FormData() object. I used to do it with a full on url-style request (and it did work!) but I want to add the option to upload images.

The form is declared a enctype="multipart/form-data", and the POST request also, but then, nothing seems to touch the php script...

Here's the code (I'm french, hence some of the variable names...):

<form method="post" id="add_form" enctype="multipart/form-data">
            <fieldset>
                <legend>Infos:</legend><br />

                <label for="add_cat">Catégory:</label>

                <select name="add_cat" id="add_cat">
                    <?php
                        $USR_CATS = $bdd->query('SELECT * FROM cats');
                        while($cat = $USR_CATS->fetch()){ 
                        ?>
                        <option <?php echo 'value="'.$cat['cat'].'"'; ?> <?php if($cat['id'] == 1){echo 'selected';}?> ><?php echo $cat['cat'] ?></option>
                    <?php
                    }
                    $USR_CATS->closeCursor();
                    ?>
                </select><br />
                <input type="button" id="add_newCat" name="add_newCat" value="Ajouter une catégorie"><br />

                <label for="add_titre">Title:</label>
                <input type="text" id="add_titre" name="add_titre" required><br />

                <label for="add_support">Support:</label>
                <input type="text" id="add_support" name="add_support" required><br />

                <label for="add_com">Commentaire du projet:</label>
                <textarea id="add_com" name="add_com" required></textarea><br />
            </fieldset>

            <fieldset id="add_infosFieldset">
                <legend>Infos Techniques:</legend><br />

                <input type="text" class="add_infos" placeholder="ex: Format: 65x84 cm" style="display:block">

                <input type="button" id="add_newInfos" name="add_newInfos" value="Ajouter une information"><br />
            </fieldset>

            <fieldset id="add_imagesFieldset">
            <legend>Images:</legend>
<input type="file" class="add_images" style="display:block">
                    <input type="button" id="add_newImagesBouton" name="add_newImagesBouton" value="Ajouter une image"><br />
            </fieldset>

            <input type="submit">
        </form>

When submitted, the results of this form goes through js:

var add_form = document.getElementById("add_form");
add_form.addEventListener("submit", function(e){
    e.preventDefault();
    add_formData = new FormData();

    //Basic infos
    add_formData.append("add_prjt", true);
    add_formData.append("add_cat", document.getElementById("add_cat").value);
    add_formData.append("add_titre", document.getElementById("add_titre").value);
    add_formData.append("add_support", document.getElementById("add_support").value);
    add_formData.append("add_com", document.getElementById("add_com").value);

    //I had, for that, to make a loop because I want the user to be able to create and fill as many fields as he/she wants
    var infos = document.getElementsByClassName("add_infos"); 
    var infosCh = ""; //So I'm creating a string which will contain them all

    for(var i = 0; i < infos.length; i ++){ 
        infosCh += infos[i].value + "<br />"; //Concatening everything so that the different infos are separated by <br />
    }
    add_formData.append("add_infos", infosCh);

//And then a bunch of shenaningans regarding the number of images people want to upload, so that there can be as much upload buttons as they want, each of them containing several images
    if(add_nbreBoutonsImages > 0){ 
        add_formData.append("add_nbreBoutonsImages", add_nbreBoutonsImages);

        var add_nbreImages = 0; 

        for(var j = 1; j < add_nbreBoutonsImages; j++){
            var nbreImagesUpload = document.getElementById("add_newImages"+j).files.length; //On regarde combien d'images y a été sélectionné
                for(var x = 0; x < nbreImagesUpload; x++){ //Et pour chacune d'entres elles
                    add_nbreImages++;
                    add_formData.append("add_image"+add_nbreImages, document.getElementById("add_newImages"+j).files[x], "add_image"+add_nbreImages);
                }
            }
        }

    //add_formData.contentType = false;
    //add_formData.processData =false;
    //I tried with and without those, but they doesn't seem to work without jQuery


//The problem must come from here...
    var req = new XMLHttpRequest();

    req.open("POST", "add.php", true);
    req.setRequestHeader("Content-Type", "multipart/form-data");
    req.send(add_formData);

});

I had a more advanced version of the request/sending step, but I tried keeping it as simple as possible first, trying to make it work

And then the php

if(isset($_POST['add_titre'])){
        $fichierFichier = fopen('fichier.txt', 'a+');
        fputs($fichierFichier, 'ça a marché...');
    }

For now I'm just trying to see if PHP gets anything at all... But even those simple instructions doesn't get executed... As if PHP is not getting the variables?

I don't get it... And the frustrating part is that nothing appears to be not working, no error message, nothing... Just the big white blank

Anyway, thanks for your time!

  • 1
    Add `print_r($_POST);` to the PHP and then check the browser debugger for what is sent back to the browser from that – RiggsFolly Jul 11 '19 at 17:10
  • Made me appear an "Array()" at the start of the page, but nothing in the debugger. Telling me there's no problem theoretically, it's just not receiving the data.. – Arthur Kuhn Jul 11 '19 at 17:48
  • Sorry I dont understand! Can you put what you get into your question please – RiggsFolly Jul 11 '19 at 17:49
  • (I edited my above post, sorry I hit enter too soon, haha) – Arthur Kuhn Jul 11 '19 at 17:50
  • You're not sending the add_formdata in your ajax request. You need to hold it in a variable prior to sending it. Read [this post](https://stackoverflow.com/a/13612240/1675954) – Rachel Gallen Jul 12 '19 at 02:17
  • Thanks Rachel! But I'm not sure if this solution works here, I used to send data this way, as a string of "variable1=data1&variable2=data2...", but it's limiting me to text content, and I want to add the option of uploading images. In my code I'm setting add_formData as a FormData object, and from what I've read in the MDN, it's not supposed to be more complicated than that, but maybe I'm wrong? – Arthur Kuhn Jul 12 '19 at 15:32

1 Answers1

0

Quick update on the situation: The problem comes as soon as I'm trying to send something to PHP using ajax with the encapuslation "multipart/data-form".

I realised that even another script from the same project stopped working as soon as I modified my ajaxPost script (which I use to send things via POST through ajax, original name), it looks like this:

function ajaxPost(url, data, callback, isData){
    var req = new XMLHttpRequest();

    req.open("POST", url); 

    req.addEventListener("load", function(){
        if(req.status >= 200 || req.status < 400){
            callback(req.responseText);
        }
        else{
            console.error(req.status + " " + req.statusText + " " + url);
        }
    });

    req.addEventListener("error",function(){ 
        console.error("Erreur réseau avec l'url: " + url);
    });

    //Ajout pour contrôler ou non si on envoie au format JSON
    if(isData){
        req.setRequestHeader("Content-Type", "multipart/form-data");
    }
    else{
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    }
    req.send(data); 
}

As long as I'm calling it and specifiying I want a "application/x-www-form-urlencoded", it goes okay. But when I try the other option, it stops working, either sending a formData or a simple string.

I've checked my php.ini config file, and the file_upload is on. And when the form is itself a enctype=multipart/form-data, and I bypass the javascript step, it works...

Tricky thing is, I need all the informations at once, so that everytinhg can be placed properly, the images in the folder named after the project of which the page is being created, etc...

So, basically still at the same spot, but with a clearer understanding... Is there anyway my php might be configured to block such cross-langage thing? Maybe I'm not understanding correctly the FormData, and not setting it up properly?

  • Please update your question by editing it. This is not an answer. P.s. I only saw your comment now. You can 'tag' a user so that the message goes to their inbox by using the @ symbol before their handle. E.g. '@RachelGallen'. – Rachel Gallen Jul 13 '19 at 00:42