Sending file together with form data via ajax post

前端 未结 3 1810
忘了有多久
忘了有多久 2020-12-05 11:22

I\'m trying to upload a file via ajax together with some fields in a form. However, it doesn\'t work. I get this error.

Undefined Index :- File

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 11:49

    you can use FormData

    $("#add_product").click(function(e){
        e.preventDefault();
        var fdata = new FormData()
        
       fdata.append("product_name",$("product_name").val());
      
        if($("#file")[0].files.length>0)
           fdata.append("file",$("#file")[0].files[0])
        //d = $("#add_new_product").serialize();
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data:fdata,
            contentType: false,
            processData: false, 
            success: function(response)
            {
                //
                alert(response);
    
            }
        })
    });
      
        

提交回复
热议问题