I want to upload an image using jQuery asynchronously with data... but cannot upload it... Only data variables can be fetch there in process page but cannot get the image file using $_FILES......
img_upload.php
<form name="frm" id="frm" novalidate enctype="multipart/form-data">
<input type="text" id="txt_name" name="txt_name" />
<input type="file" name="img_upload" id="img_upload">
</form>
img_upload.js
$(function() {
$("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
var txt_name = $("input#txt_name").val();
var FileImgData = $('#img_upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', FileImgData);
$.ajax({
url: "./img_upload_p.php",
type: "POST",
data: {
txt_name: txt_name,
upload_photo: FileImgData
},
cache: false,
})
},
});
});
img_upload_p.php
$str_name="";
if(isset($_POST["txt_name"])) { $str_name=trim($_POST["txt_name"]); }
$str_upload_photo="";
if(isset($_FILES['file_photo']))
{ $str_upload_photo = trim($_FILES['file_photo']['name']); }
Please suggest me that image variable declared (upload_photo: FileImgData) in JQuery file "img_upload_p.js" is correct or not.
Also, the way image file variable is fetched in "img_upload_p.php" is correct or not.
if any of them are wrong then how can I assign that image variable in JQuery file and fetch in PHP process page...
PHP image upload code is ready and in working condition... but just having issue with above two mentioned points...
img_upload.js
$(function() {
$("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
var formData = new FormData();
formData.append("hdn_pkid", $("input#hdn_pkid").val()); // if hidden variable is passed
formData.append("txt_name",$("input#txt_name").val()); // if other input types are passed like textbox, textarea, select etc...
formData.append('img_upload', $('input[type=file]')[0].files[0]); // if image or other file is passed
$.ajax({
url: "./img_upload_p.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
cache: false,
})
},
});
});
img_upload_p.php
Get all variables' value using POST method and store them in new variables to use and process on this page as usual.
Get file variable like below mentioned code and then upload image using normal PHP function or your own way.
if(isset($_FILES['img_upload']))
{ $str_ = trim($_FILES['img_upload']['name']); }
One of the best way to do this is use Dropzone js, this is a best library for uploading files using ajax and it also provides progress bar. You can use your own PHP(or any other server side language) code at server side.
I hope it will helpful.