0

in PHP page with multiple form tag to register user information. using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.

my html code:

<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>

Javascript Code:

let data1 = document.getElementById('data1').value,
    data2 = document.getElementById('data1').value,
    data3 = document.getElementById('data1').value,
    upimage = document.getElementById('upimage').value;
$.ajax({
    url:"././newregister.php",
    method:"POST",
    data:{action:'newregister', data1:data1, data2:data2,
        data3:data3, upimage:upimage},
    success:function(data){
        alert(data);
    }
});

newregister php code:

$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
    echo "Sucsess"; 
}
else
{
    echo "Error" . $_FILES["file"]["error"] ; 
}

ERR: Undefined index: file in .... on line ....

STATICMAN
  • 13
  • 5
  • You should post a [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object. – ferikeem May 26 '21 at 11:17
  • i know but to manage my data in register php file i need to send it by data. – STATICMAN May 26 '21 at 11:19
  • Do you know how convert this type of data to FormData by append or otherway? – STATICMAN May 26 '21 at 11:21
  • You create a FormData object (new FormData()), then append the values to it. Another way may be to set up a form in html, with type (method?) multipart/formdata, and post that with a submit button/function. – ferikeem May 26 '21 at 11:25

2 Answers2

1

Given by POST method uploads

Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.


As ferikeem already said. Wrap your data in a FormData Object and send it that way. See: https://stackoverflow.com/a/5976031/10887013

JavaScript

let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);

$.ajax({
    url: "././newregister.php",
    method: "POST",
    data: fd,
    processData: false,
    contentType: false,
    success: function(data){
        alert(data);
    }
});

Michael
  • 51
  • 4
0

$_FILES["file"], here is your problem.

In $_FILES array key "file" doesn't exists. As I see you need to change $_FILES["file"] with $_FILES["upimage"].

Obsidian
  • 3,719
  • 8
  • 17
  • 30
krusu
  • 1
  • 1