Uploading a File from a Bootstrap Modal Using Ajax

Uploading a file from a bootstrap modal using ajax

Change the data value in your Ajax post to postData. postData contains the form data.

Change this section

data: data,

To

data: postData,//this contains the form data

file uploading in PHP & Ajax from bootstrap modal

Finally I found the solution. Basically I've changed the ajax formdata and restructured my insert.php file.

Below link helped me to understand the idea.

https://www.codexworld.com/ajax-file-upload-with-form-data-jquery-php-mysql/

my modified ajax is as below

        $.ajax({
type : 'POST', // define the type of HTTP verb we want to use POST
enctype : 'multipart/form-data',
url : 'insert.php', // the url where we want to POST
data : new FormData(this),
dataType : 'json',
contentType : false,
cache : false,
processData : false,
})

File upload through a modal using Ajax

You can upload the file using bootstrap modal via ajax like this.

In your form tag use attribute enctype and form html will be like below:

 <form enctype="multipart/form-data" id="modal_form_id"  method="POST" >
<input type="file" name="documents">
</form>

Js code:

    var postData = new FormData($("#modal_form_id")[0]);

$.ajax({
type:'POST',
url:'your-post-url',
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log("File Uploaded");
}

});

On your controller side you can do in the function like below to upload image.

    if(Input::hasFile('documents')) {

$path = "directory where you wish to upload file";

$file_name= Input::file('documents');
$original_file_name = $file_name->getClientOriginalName();

$extension = $file_name->getClientOriginalExtension();
$fileWithoutExt = str_replace(".","",basename($original_file_name, $extension));
$updated_fileName = $fileWithoutExt."_".rand(0,99).".".$extension;

$uploaded = $file_name->move($path, $updated_fileName);

echo $updated_fileName;

}

How to post a file and form data from a Bootstrap Modal

Other fields are not passed because you are not appending them to the FormData, a better way is to use the form object while initializing the FormData() rather appending all the form input manually, see below,

Note: add the attribute id="my-form" to the form before using it

$(document).ready(function(){
$('#upload').click(function(){

event.preventDefault();
var form = $("#my-form")[0];
var data = new FormData(form);
// AJAX request
$.ajax({
url: 'clienttest.php',
type: 'post',
data: data,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
// Show image preview
$('#preview').html(" Process Started");
}else{
alert('file not uploaded');
}
}
});
});
});


Related Topics



Leave a reply



Submit