Why ajax is not posting file data to php page?

//IN JS
function serialize(form, postData = null, widget = null, alert = null, redirect = null) {
  var data;
  var formData = new FormData();

    if (!form || form.node.nodeName !== "FORM") {
        return;
    }
    var i, j, q = []; // not all used I modified ready form handle code to use FormData.

    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        switch (form.elements[i].nodeName) {
        case 'INPUT':
            switch (form.elements[i].type) {
            case 'text':
            case 'hidden':
            case 'password':
            case 'button':
            case 'reset':
            case 'submit':
                formData.append(form.elements[i].name,form.elements[i].value );
                break;
            case 'checkbox':
            case 'radio':
                if (form.elements[i].checked) {
                }
                break;
            case 'file':
formData.append(form.elements[i].name,form.elements[i].files[0], form.elements[i].files[0].name);

            break;
            }
            break;
        case 'TEXTAREA': break;
        case 'SELECT':
            switch (form.elements[i].type) {
            case 'select-one': break;
            case 'select-multiple':
                for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                    if (form.elements[i].options[j].selected) {
                    }
                }
                break;
            }
            break;
        case 'BUTTON':
            switch (form.elements[i].type) {
            case 'reset':
            case 'submit':
            case 'button':
                formData.append(form.elements[i].name, form.elements[i].value);
                break;
            }
            break;
        }
    } 
    formData.append(postData,""); //Some additional keywords with empty value nothing special
    //I could do it also like this to ensure I posted but nothing works for file input if I change it to text that is posted.
    //formData.append("imgfile", document.getElementById("imgfile").files[0]); 





var xhttp = new XMLHttpRequest();

 xhttp.onreadystatechange = function()
 {

    if (this.readyState == 4 && this.status == 200)
    {
      if(this.responseText == 0)
      { 
        var t = document.createTextNode("no response text");

        if(widget!=null){widget.appendChild(t);}
        //if(redirect!=null){window.location.replace(redirect);}else{window.location.replace("index.php");}
      }
      else
      {var t = document.createTextNode(this.responseText);

        if(widget!=null){widget.appendChild(t);}
      }
    }
  };

  xhttp.open("POST", "ajax.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(formData);




}


//IN PHP
if(isset($_POST['postIdea'])){ //There were some others but I just used one here.
    echo basename($_FILES['imgfile']['name']);

}

as a response text I get “undefined index imgfile …” //file input name and id is “imgfile” and it is located in form. Can anyone explain what am I missing here ?

If you console.log(formData) does that give any clues?

Show us your form… (at least the relevant bits)

You can’t URL encode binary files, so you should set the header to multipart/form-data (or actually just omit it). BTW you don’t have to .append() all the input data manually, you can create a FormData object directly from the form like so:

var sendForm = function (form) {
  var xhr = new XMLHttpRequest()
  var formData = new FormData(form)

  xhr.open('POST', 'ajax.php')
  xhr.send(formData)
}

File(126008) {name: “1_Purple.jpg”, lastModified: 1495130459503, lastModifiedDate: Thu May 18 2017 21:00:59 GMT+0300 (GMT+03:00), webkitRelativePath: “”, size: 126008, …}

Yes it reads it like this. I also get the name as “imgfile”; but when I try to get it like $_FILES[‘imgfile’]["name "] fails.

OK, maybe you could var_dump() the $_POST and $_FILES array and see what you get.

Might it have anything to do with mixing arrays and objects?

Alright I found the solution checking console also helped a lot to eliminate possiblities. The issue was, I put form’s “enctype” as “type” [quote=“m_hutley, post:3, topic:296804, full:true”]
Show us your form… (at least the relevant bits)
[/quote]

One more important thing:

  xhttp.open("POST", "ajax.php", true);
  //xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(formData);

Do NOT use “setRequest” header.
yes that was right. After reading it I fixed everything. I did not think I can do this kind of easy mistake. Thanks.

The more experienced you get, the more you realize you will do the easy mistakes :wink:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.