Search code examples
phpjqueryajaxjquery-ajaxq

Upload and save to database with php and jquery ajax


i'm a amateur programer. I'm coding upload and insert to database function with php and jquery ajax but it not work my form

<form>
<input type="file" id='iputfile1' />
</form>

my jquery script

 iputfile1 = $("#iputfile1").val();
jQuery.ajax({
        type:"POST",
        url:"ex.php", //goi toi file ajax.php
            data:"filename"=filename+"&+"&iputfile1="
        +iputfile1,
        success:function(html){
         jQuery("#responseDiv").show();
         jQuery("#responseDiv").html(html);
        }
       });

my ex.php file

$iputfile1 = $_REQUEST['iputfile1'];
print_r($iputfile1)

after select file and submit my ex.php file not recivice $_file['tmp']


Solution

  • <input type="file" class="file">
    
    
    $(".file").on("change",function(){
       var file = new FormData();
       file.append('file',$('.file')[0].files[0]);
       $.ajax({
        url: "upload.php",
        type: "POST",
        data: file,
        processData: false,
        contentType: false, 
         beforeSend:function(){
        $(".result").text("Loading ...");
         }, 
         success:function(data){
          $(".result").html(data);
        }
    });
    
    
    <div class="result"></div>
    
    in upload.php
    
    
    <?php
    include("database.php");
    $name = $_FILES["file"]["name"];
    if(move_uploaded_file($_FILES["file"]["tmp_name"], "DESTINATION/".$name)){
          // insert to data base
          echo '<img src="DESTINATION/'.$name.'">';
    }
    ?>