For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});
Related
Here is my sample code which I got from a website which converts xls to xlsx. It downloads the file immediately after converting it to xlsx, so I want to use that file further as blob. so is there any way to use that file which I will receive from action method using JavaScript?
Thank you!
HTML Code :
<form action="https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&download=attachment" method="post" enctype="multipart/form-data">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="anyName" />
<input type="submit" value="Convert file"/>
</form>
JavaScript code:
function convert(input){
let obj = {
File : input,
FileName : 'Test'
}
$.ajax({
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&StoreFile=true',
method: 'POST',
headers:{
'content-type' : 'multipart/form-data'
},
body: JSON.stringify(obj),
success : function(res){
console.log(res);
},
error: function(err){
console.log(err.responseText);
}
})
}
you would use javascript's fetch() to upload the file to the conversion endpoint instead of using a form, then you would get the file download as a response, which you can do with what you like.
this question may help you figure out how to upload a file, but you will have to understand a bit of javascript:
How do I upload a file with the JS fetch API?
I tried to upload same way as you mentioned #dqhendricks but didn't worked for me.
when I tried with FormData it worked for me. It would be awesome if we could do it with just JS.
HTML :
<form method="post" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="newFile" />
<input type="button" id="btnSubmit" value="Convert file"/>
</form>
JS:
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
var form = $('#fileUploadForm')[0];
var d = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=[Secret]&StoreFile=true',
processData: false,
contentType: false,
cache: false,
data: d,
timeout: 600000,
success: function (res) {
console.log(res);
},
error: function (err) {
console.log(err.responseText);
}
})
});
});
in my form code there is text input, checkbox input, file input type...etc,
everything working fine except the file input it's only taking one value ( multiple files upload isn't sending through ajax call ) how can i send arrays inside the serialize() function ?
Code :
<form action="#" id="postAdd" enctype="multipart/form-data">
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file[]" multiple required>
<input autocomplete="off" type="text" class="form-control bg-white" name="discName[]">
<button id="postAdbtn" class="btn btn-primary d-block mt-2">Submit</button>
</form> $(document).ready(function() {
$('#postAdbtn').click(function() {
var form = $('#postAdd').serialize();
$.ajax({
url: 'add-product-done.php',
method: "POST",
data: {
form: form
},
success: function(data) {
$('.fetchData').html(data);
}
})
});
});
one more thing, how can i get the files in PHP ?
and thanks
Can you try something like this?
var form = new FormData($("postAdd"));
$.ajax({
url: 'add-product-done.php',
data: form,
contentType: "multipart/form-data",
type: 'POST',
success: function(data){
console.log(data);
},
error: function(err){
console.error(err);
}
});
I've seen lots of questions on this subject, but none of them seem to address my issue. It all seems pretty straight forward, but I just get a blank array, am I missing something really simple here?
Thanks.
Here is the html / javascript code:
<script type="text/javascript" src="/javascript/jquery.js"></script>
<form enctype="multipart/form-data" action="" id="frmProduct" method="post">
<input type="file" id="pdffile" name="pdffile" size="50" />
<br />
<input id="pdffileupload" type="submit" value="Upload" />
</form>
<script>
$('#pdffileupload').bind('click', function ()
{
var files=document.getElementById('pdffile').files[0];
var fd = new FormData();
fd.append( "pdffile", files);
$.ajax({
url: '/info.php',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function(data) { alert("YES"); },
error: function(data){ alert("NO"); }
});
return false;
});
</script>
& PHP info.php
<?php
var_dump($_FILES);
?>
Changes needed (just check once by trying all my suggestions):-
1.In the same folder put both files (same working directory).
Code changes:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <!-- add jquery library like this -->
<form enctype="multipart/form-data" action="" id="frmProduct" method="post">
<input type="file" id="pdffile" name="pdffile" size="50" />
<br />
<input id="pdffileupload" type="submit" value="Upload" />
</form>
<script>
$('#pdffileupload').bind('click', function ()
{
var files=document.getElementById('pdffile').files[0];
var fd = new FormData();
fd.append( "pdffile", files);
$.ajax({
url: 'info.php', // remove /
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function(data) { alert("YES"); },
error: function(data){ alert("NO"); }
});
return false;
});
</script>
And in php
<?php
print_r($_FILES);
?>
Note:- Check in your browser console (response tab).
You might try this:
<?php print_r($_FILES); ?>
instead of
<?php var_dump($_FILES); ?>
Because the var_dump doesn't work with $_FILES.
I want to Upload photos by using Ajax Post method,
Here is my html and javascript code
<script>
$(document).ready(function(){
$('#multiple_upload_form').submit(function(e){
e.preventDefault();
var upload = $('#images').val();
$.ajax({
type:'POST',
url:'album.php',
data:
{
upload : images
},
cache:false,
contentType:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
},
error:function()
{
$('#image_preview').html('error');
}
});
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Album Name</label>
<input type="text" name="aname" class="form-control" id="aname">
</div>
<div class="form-group">
<label for="file">Upload Photos:</label>
<input type="file" id="images" name="images" />
</div>
<div id="images_preview"></div>
</div>
<center class="feedback" style="display:none">Loading...</center>
<button id="submit" name="submitt" class="btn btn-default">Submit</button>
</form>
and this is my PHP CODING
if(isset($_FILES['images']['name']) )
{
$img = $_FILES['images']['name'];
if(!empty($img))
{
echo 'MaxSteel';
}
}
else
{
echo 'Same Problem';
}
I am having undefine index : images
it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem
Go through this code, it may help
var data = new FormData();
data.append("Avatar", file.files[0]);
$.ajax({
url: "http://192.168.1.1:2002/,
type: "POST",
data:data,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.
You can use var_dump($file) to see the $_FILE content.
You need to be sending your data through FormData().
Try something like this:
var images = $("#images").get(0).files;
var formData = new FormData();
$.each(images, function(i, image) {
data.append("images[]", image);
});
Then send formData as your $.ajax data.
I'm search in the internet for a solution. I find some of them but they didn't work for me. Basically I have an input form on a laravel project where I want to upload an image with ajax request.
On the Get request instead of sending the image is sending the following parameter value [object%20FormData]
I know that I'm doing something wrong but I don't know what it is. Can anyone help me? Here is my Html code
<form class="form-horizontal" id="upload" enctype="multipart/form-data" action="{{{ URL::route('upload') }}}" autocomplete="off" onsubmit="return false">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="file" name="image" id="image" />
<button type="button" id="upload_image_btn" class="btn btn-default">Upload!</button>
</form>
And here is my ajax code
var image = $('#image')[0].files[0];
formdata = new FormData();
formdata.append( 'image', image );
formdata.append( 'action', 'image' );
$.ajax({
type: "GET",
url: '{{{ URL::route('upload') }}}',
data: formdata,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var errors = data.responseJSON;
$.each(errors, function (key, data) {
$.each(data, function (index, data) {
$(".upload_error").text(data);
})
})
}
});
Can anyone help me to find what I'm doing wrong? Thank you
SOLUTION: as the comment says, I changed the GET request of ajax to POST and it work. Thank you for your help