HTML:
<input type="text" name="description">
<input type="file" name="image" accept=".jpg">
How can I use $.ajax to upload the image and text value? I have no problem producing an object to submit text data, but have no idea where to start with the image.
I am using PHP server-side, so encoding the image in base64 or similar methods are perfectly acceptable.
it’s easiest to use the FormData() class:
So now you have a FormData object, ready to be sent along with the XMLHttpRequest. and append fields with FormData Object
<script type="text/javascript">
$(document).ready(function () {
var form = $('form'); //valid form selector
form.on('submit', function (c) {
c.preventDefault();
var data = new FormData();
$.each($(':input', form ), function(i, fileds){
data.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('input[type=file]',form )[0].files, function (i, file) {
data.append(file.name, file);
});
$.ajax({
url: '/post_url_here',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (c) {
//code here if you want to show any success message
}
});
return false;
});
})
</script>
and forcing jQuery not to add a Content-Type header for you, otherwise, the upload file boundary string will be missing from it.
Use jQuery form js to upload images using ajax.
Check https://github.com/malsup/form/
var options = {
url : 'url',
success : function(responseText) { "event after success "}
};
$(" form id ").ajaxSubmit(options);
and get image in php file and upload images
Related
This question already has answers here:
Sending multipart/formdata with jQuery.ajax
(13 answers)
Closed 6 years ago.
I would like to pass form data via jquery to a php page. Now I am little confused with image passing through jquery and how it will reach php page.
My code:
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var guestbookSendMessage = { //Fetch form data
'name' : $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file' :$("#fileInput")[0].files[0];
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'php/process.php', //Your form processing file url
data : guestbookSendMessage, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
You may use File API or FormData to send image data to your server with ajax. What to choose is up to you to decide but since FormData is easier to implement I will answer your question using FormData here.
First of all you need to create FormData container and append your data to it. Just amend your code
var guestbookSendMessage = { //Fetch form data
'name': $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file': $("#fileInput")[0].files[0];
};
with this
var guestbookSendMessage = new FormData();
guestbookSendMessage.append('name', $('input[name=name]').val());
guestbookSendMessage.append('msg', $('textarea[name=msg]').val());
guestbookSendMessage.append('file', $("#fileInput")[0].files[0]);
Now instead of this parameter in your $.ajax
dataType: 'json'
Add these two
processData: false,
contentType: false
This will allow your data to be interpreted correctly.
Now in your php/process.php script you'll get 'name' and 'msg' in your $_POST superglobal array and 'file' in $_FILES.
var fdata = new FormData();
var myform = $('#prfform'); // specify the form element
var idata = myform.serializeArray();
var document = $('input[type="file"]')[0].files[0];
fdata.append('document[]', document);
$.each(idata,function(key,input){
fdata.append(input.name,input.value);
});
$.ajax({
url:"process.php",
type: "POST",
data: fdata,
processData: false,
contentType: false,
beforeSend: function() {
//something before send
},
success:function(data) {
//something after response
}
});
<form name="prfform" id="prfform" method="post" enctype="multipart/form-data">
<!-- elements -->
</form>
Please try this code.
"enctype" is important in the form.
In ajax script, give "processData: false" and "contentType: false"
This might solve your issue.
I am doing an ajax popup to upload image into filesystem. The image uploading process has the following steps..
choosing the file and crop it to needed size.
the result image is displayed in <img> tag src as Base64 Code.
converting the Base64 to Blob to send via ajax
Here is the code...
$(document).ready(function(){
$('#btn_save').on('click', function () {
var PaymentStatus = $("#PaymentStatus").val();
var image = $('#image-id').val();
var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');
var formData = new FormData();
formData.append('picture', blob);
formData.append('PaymentStatus', PaymentStatus);
$.ajax({
data: formData,
url:"/login/advshop/add",
method: 'GET',
processData: false,
contentType: false,
success: function (result) {
alert("form submitted");
},
error: function (result) {
alert('error');
//alert(result);
}
});
});
});
but I am not able to get the data in my controller..
public function add() {
print_r($_POST['picture']);
}
and the error message is..
Message: Undefined index: picture
please see my answer..
$(document).ready(function () {
$('#btn_save').on('click', function () {
var image = $('#image-id').val();
var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var PaymentStatus = $("#PaymentStatus").val();
var formData = new FormData();
formData.append('image', base64ImageContent);
formData.append('PaymentStatus', PaymentStatus);
$.ajax({
data: formData,
url: "/login/advshop/add",
method: 'POST',
processData: false,
contentType: false,
success: function (result) {
alert("form submitted");
},
error: function (result) {
alert('error');
//alert(result);
}
});
});
})
In Controller.
public function add() {
$data = base64_decode($_POST['image']);
file_put_contents('images/test.jpg', $data);
}
you can directly pass the Base64 image content via ajax using formData append.decode the base64 content and put it in file_put_contents() function.
i think the issue is that you wanna convert the uploaded image into base64 string and then you wanna pass this string to controller via ajax ..is it brother..
i too faced that problem..so first take a hiddenfield in your form and give id and value for hiddenfield as value of hidden field is the converted string .then you can easily get the value of hiddenfield i.e. base64 string into a variable in js by getElementById then pass the variable to controller..there youcan access through $_POST['id of hiddenfield']. then you can store the value into database directly by save().
yes ,no need to convert base64 to string..base64 returns string so u use this string to value of hiddenfield.
firts of all, thank you for all the help you have been giving me allways with your answers. I'm really new with coding, but more or less I get through and I'm creating a website from 0 (www.mundopedales.com)
But today I'm really stuck with a form I want it to do two action, sending data to MySQL db and uploading a image file with a custom name. I'm able to run both but not at the same time, if one works the other one doesn't.
Form action runs this file where I can send the input text for the custom name and the image:
<form action="upload.php" id="send-bike" method="post" enctype="multipart/form-data">
<input type='text' name='newname' id='newname' placeholder='Image filename'/>
<input type="file" name="fileToUpload" id="fileToUpload">
Button :
<input id="postData" type="button" value = "post">
Ajax code is this and is where I get curious action hapening:
$('#postData').click(function (e) {
e.preventDefault();
var newname = $('#newname').val();
var dataString = 'newname=' + newname;
$.ajax({
type: 'POST',
url: 'sendbike.php',
data: dataString,
success: function () {
$('#send-bike').submit();
//window.location.assign('http://www.mundopedales.com/crear-bicicletas.php');//if I untag this line I change upload.php to work and then sendbike.php runs....
}
});
});
Don't understand why that makes that change and how I can do to make both run at the same time.
Thanks in advance and sorry for my poor English (made in Spain...)
Use .submit() of jQuery instead.
$('#send-bike').submit(function(){
var formData = new FormData($(this)[0]); /* DATA FROM THIS FORM */
$.ajax({
type: 'POST',
url: 'sendbike.php',
data: formData,
contentType: false,
processData: false,
success: function () {
alert('success uploading!');
}
});
return false;
});
Just process the submitted data to sendbike.php.
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.
I'm trying to implement a HTML5 ajax file upload with the help of HTML5's File API. It is based on Afzaal Ahmad Zeeshan's answer to this question.
My main aim would be to be able to let users upload .xls and .xlsx spreadsheet for later use.
HTML
<form class="form-uploadXLS" method="post" action="php/uploadXLS.php" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-12">
<input type="file" name="xls" class="xls" />
</div>
</div>
<input type="button" value="Upload" class="btn-uploadXLS" />
</form>
<progress></progress>
And here are the jQuery event handlers, just like in the above mentioned answer:
File input onChange event:
$('.xls').on('change', function () {
var file = this.files[0];
var fileName = file.name;
var fileType = file.type;
var fileSize = file.size;
console.log("file name: " + fileName + ", type: " + fileType + ", size: " + fileSize);
});
This works correctly, the file's name, type and size gets logged to the server.
Upload button's onClick event:
$('.btn-uploadXLS').on('click', function (event) {
event.preventDefault();
console.log("Upload button clicked");
var formData = new FormData($('.form-uploadXLS')[0]);
$.ajax({
url: 'php/uploadXLS.php', //Server script to process data
type: 'POST',
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function (stuff) {
console.log("BeforeSend");
console.log(stuff);
},
success: function (data) {
console.log("Success!");
console.log(data);
},
error: function (error) {
console.log("Error!");
console.log(error);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
On server side, I'm using this PHP code to check if the file has been sent to the server
if(!empty($_FILES['xls'])) {
echo '<pre>',print_r($_FILES,1),'</pre>';
}
else {
die('no $_FILES variable');
}
And here's the result of print_r:
Array
(
[xls] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
According to the documentation, error code 4 means: UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
What am I doing wrong?
Edit:
If I disable the click event listener and submit the form as normal, the file gets uploaded without problems.
I've noticed, that the formData variable doesn't have any value. This is the value of formData after it's been set: FormData { append=append()}
For some reason the problem was with the formData variable, previously defined as such:
var formData = new FormData($('.form-uploadXLS')[0]);
I've changed the index to 1 like this..
var formData = new FormData($('.form-uploadXLS')[1]);
.. and for some reason it works now.
Instead of:
if(!empty($_FILES['xls'])) {
try this:
if(!empty($_FILES['xls']['name'])) {
type = $_FILES['xls']['type'])
tmp = $_FILES['xls']['tmp_name'])