简体   繁体   中英

sending input type file using ajax

ok i been stuck witht his for hours, i just want to upload users profil pic using ajax but i cant get to send the file to ajax2.PHP that do the upload! this is my code

    <script>
    $(document).ready(function(){

        //trigger change picture when click on the picture
          $("#changelogox").on('click', function() {
            $('#logopicsxda').click();
        });


    });
    </script>
    <script>

    $(function(){ 
            $('#savelogox').click(function(){
                  var formData = new FormData($('#ff')[0])


                $.ajax({

                    type:"POST",
                    url:"ajax2.php",
                    data:'act=save'+FormData,
                    success: function(data){

    alert(data);
                    }
                });
     });
     });



    </script>
    <form id="ff" action="" method="post" enctype="multipart/form-data">
    <img  id="logoc" src="images/logo2.jpg" class="logo">
    <span id="contacxkr"><span class="xaox" id="changelogox">Change</span>
    <br>
    <br>

    <span class="xaoxx" id="savelogox">save</span></span>

        <input type="hidden" name="MAX_FILE_SIZE" value="2048000" />

    <input  style="display: none;" name="myimage" type='file' multiple accept='image/*' id='logopicsxda' /></form>

and this is my ajax2.php code which does the uplaod to the server and database

<?php

include('core/init.php');
    extract($_POST);
$username=$user_data['username'];


            $posted_data = print_r($_POST,true);
file_put_contents('debug.txt',$posted_data);


    if($act == 'save'): //if the user click on "like"



             include 'config2.php';

        $file = $_FILES['myimage'];

$file_name = $file['name'];


$error = ''; // Empty

// Get File Extension (if any)

$ext = strtolower(substr(strrchr($file_name, "."), 1));

// Check for a correct extension. The image file hasn't an extension? Add one

   if($validation_type == 1)
   {
   $file_info = getimagesize($_FILES['myimage']['tmp_name']);

      if(empty($file_info)) // No Image?
      {
      $error .= "ERROR! The uploaded file doesn't seem to be an image.";
      }
      else // An Image?
      {
      $file_mime = $file_info['mime'];


         if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
         {
         $extension = $ext;
         }
         else
         {
         $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
         }

         if(!$extension)
         {
         $extension = '';  
         $file_name = str_replace('.', '', $file_name); 
         }
      }
   }
   else if($validation_type == 2)
   {
      if(!in_array($ext, $image_extensions_allowed))
      {
      $exts = implode(', ',$image_extensions_allowed);
      $error .= "ERROR! You must upload a file with one of the following extensions: ".$exts;
      }

      $extension = $ext;
   }

   if($error == "") // No errors were found?
   {
   $new_file_name = strtolower($file_name);
   $new_file_name = str_replace(' ', '-', $new_file_name);
   $new_file_name = substr($new_file_name, 0, -strlen($ext));
   $new_file_name .= $extension;
  $new_file_name = uniqid() . $username.$new_file_name;

   // File Name

   $move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);


   if($move_file)
       {
$query= $pdo->prepare("UPDATE users SET profilepic=?  WHERE username= ?");

        $query->bindValue(1,$new_file_name);
            $query->bindValue(2,$username);
        $query->execute();




       }
   }
   else
   {
   @unlink($file['tmp_name']);
   }
    endif;

?> 

the problem is i cant figure out how to send the file to ajax2.php when i debug it i get this

Array
(
    [act] => savefunction FormData() { [native code] }
)

If you want to add more fields to an ajax request using FormData, you have to append the data to the object

var formData = new FormData($('#ff')[0]);
formData.append('act','save');

also for $.ajax to work with FormData you have to set contentType and processData to false.

 $.ajax({

    type:"POST",
    url:"ajax2.php",
    data: formData,
    contentType: false,
    processData: false,
    success: function(data){

        alert(data);
    }
});

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