javascript - AJAX upload file and text not work -
i using ajax code submit form , upload multiple input file. want send form data via ajax. text input send file input not successful post via ajax! how change code?
$("#add_order").click(function () { //*****get data input var formdata = new formdata(); formdata.append( 'action', 'add_order'); formdata.append( 'customer_name', $('input[name=customer_name]').val()); formdata.append( 'date', $('input[name=date]').val()); formdata.append( 'order_status', $('input:radio[name=order_stautus]').val()); formdata.append( 'total_price', $('input[name=totalprice]').val()); formdata.append( 'quits', $('input[name=quits]').val()); formdata.append( 'debt', $('input[name=debt]').val()); formdata.append( 'desc', $('#desc').val()); formdata.append( 'desc2', $('#desc2').val()); $.each($("input[type=file]"), function(i, obj) { $.each(obj.files,function(j,file){ formdata.append('photo['+i+']', file); }); }); $.ajax({ url: "includes/ajax/ajax.php", data: formdata, processdata: false, contenttype: 'multipart/form-data', type: 'post', datatype:'json', success: function(response){ //load json data server , output message if(response.type == 'error'){ //load json data server , output message output = '<div class="alert alert-danger">'+response.text+'</div>'; }else{ output = '<div class="alert alert-danger">'+response.text+'</div>'; } $("#results").append(output).slidedown(); } }); });
php code form data:
if($_post['action']=='add_order'){ $customer_id = 1; $date = $_post['date']; $status = $_post['order_status']; $total_price = $_post['total_price']; $quits = $_post['quits']; $debt = $_post['debt']; $desc = $_post['desc']; $desc2 = $_post['desc2']; for($i=0; $i<count($_files['photo']['name']); $i++) { //get temp file path $tmpfilepath = $_files['photo']['tmp_name'][$i]; //make sure have filepath if ($tmpfilepath != ""){ //setup our new file path $newfilepath = "../../uploads/orders/" . $_files['photo']['name'][$i]; //upload file temp dir if(move_uploaded_file($tmpfilepath, $newfilepath)) { //handle other code here } } }
formdata console.log:
according this, contenttype
must set false ajax file uploads.
and perhaps try naming files photo[]
rather photo[n]
let php server handle array conversion. see http://php.net/manual/en/features.file-upload.multiple.php.