简体   繁体   中英

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:

HTML File:

<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">


<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>

Ajax Call:

<script>
 function createDocsVerify () {

  var data = {
   'photo1'     : jQuery('#photo1').val(),
  }; 

  //Ajax call Start Here
  jQuery.ajax({
    url : '/myproject/adminseller/sellerdocsverify.php',
    method : 'POST',
    data : data,
    success : function(data){

    if (data != 'passed') { 
     jQuery('#modal_errors_3').html(data);
    }

    if (data == 'passed') {

     jQuery('#modal_errors_3').html("");
     location.reload();
   }
   },
   error : function (){alert("Something went wrong.");},

   });    

  }
  </script>

Php File: sellerdocsverify.php

if (isset($_POST['photo1'])) {
   $photo1 = sanitize($_POST['photo1']);
   // var_dump Output: string(20) "C:\fakepath\0553.jpg" 
 }


 $errors = array();
  $required = array(
   'photo1'  => 'Please select Photo 1',
);



// check if all required fileds are fill out
foreach ($required as $field => $display) {
 if (empty($_POST[$field]) || $_POST[$field] == '') {
  $errors[] = $display.'.';
 }
 }


$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();



**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**



$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];  

$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];

$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;

if ($mimeType != 'image') {
 $errors[] = 'The file must be an image.';
}



if (!empty($errors)) {
  echo display_errors($errors);
 }else{
  echo 'passed';

   // upload file and insert into database
  if ($photoCount > 0) {        
    move_uploaded_file($tmpLoc1, $uploadPath1);
   }

$insertSql = "INSERT INTO docTable  (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);

$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';


}
?>

Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.

Any idea or suggestion would be welcome.

You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false . Your javascript should look like this:

<script>
function createDocsVerify() {
    var formdata = new FormData();
    var file = jQuery('#photo1').prop('files')[0];
    formdata.append('photo1', file);

    //Ajax call Start Here
    jQuery.ajax({
        url: '/myproject/adminseller/sellerdocsverify.php',
        method: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        data: formdata,
        success: function(data) {
            if (data != 'passed') {
                jQuery('#modal_errors_3').html(data);
            }
            if (data == 'passed') {
                jQuery('#modal_errors_3').html("");
                location.reload();
            }
        },
        error: function() {
            alert("Something went wrong.");
        },
    });
}
</script>

That should upload the photo.

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