I have html form:
<form enctype="multipart/form-data" id="formUpload">
<input type="file" name="file" />
<button type="submit" id="sub">Click</button>
</form>
My script:
$(function() {
$("#sub").on("click",function () {
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
I try to upload file in upload.php, but all is wrong.
How can I get $_FILES variable?
Every time you click on submit button, your page will get refreshed and you won't see any output from this statement $("#res").html(data);. Use event.preventDefault() method to prevent your form from being submitted in the first place. So your Javascript code should be like this:
$(function() {
$("#sub").on("click",function (event){
event.preventDefault();
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
And in the backend upload.php page, you can access the uploaded file data using $_FILES, like this:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$name = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
// ...
}
?>
Related
I'm newby with jquery and have a problem with dealing multiple multipart forms on same page. I'm trying to add some data to mysql via php also uploading mp3 files at same time. Each form uses samename+PHPID. There is no problem with first form but im not getting file data when i use other forms. Can anyone help me?
JS:
$(".msc_send_button").click(function(e) { // changed
var a = this.id; // Button id
var form = $('#'+a).parents('form').attr('id'); // Get buttons parent form id
e.preventDefault();
var formData = new FormData($('#'+form)[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
$('#'+a).html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
$('#'+a).html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
PHP Form:
<form name="music-form" id="music-form<?php echo $cont['id']; ?>" enctype="multipart/form-data" novalidate>
<input type="text" name="songno" id="songno" value="<?php echo $cont['song_no']; ?>">
<input type="file" id="mp3" name="mp3" class="inputfile" accept="audio/*" multiple>
<button type="submit" class="msc_send_button" id="msc_send_button<?php echo $cont['id']; ?>">Send</button>
</form>
I think you should change your jquery selector. I didn't see your html codes but you may have created nested forms. Maybe you can use closest('from') instead of parents('form')
$(".msc_send_button").click(function(e) { // changed
var buttonEl = $(this);
var form = buttonEl.closest('form');
e.preventDefault();
var formData = new FormData(form[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
buttonEl.html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
buttonEl.html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
I am trying to send the form data to PHP with AJAX but when dumping data on PHP page it is returning null values.
Actually, I want a program where I can upload an image than in pop up crop it and then save the cropped image in the database.
My code is given below:
$('#fileinput').on('change', function() {
var formD = new FormData();
var file = $('#fileinput')[0].files[0];
// var nfile = file.serializeArray();
// console.log(file);
formD.append('file', file);
formD.append("clientID", 2993);
console.log(formD);
$.ajax({
url: 'croped.php',
type: 'POST',
data: {
'ff': formD
},
processData: false,
contentType: true,
// dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" id="fileinput" />
<input type="submit" name="upld" id="upldbtn" />
</form>
croped.php
<?php
var_dump($_POST);
echo "ll";
?>
Please let me know what I am missing or doing wrong.
Try this, it works for me :)
contentType: false,
data: formD,
For example
$.ajax({
url: "croped.php",
type: "POST",
data: formD,
processData: false,
contentType: false,
// dataType: 'json',
success: function (data) {
console.log(data);
},
});
For the php code
<?php
echo "<pre>";
print_r($_FILES);
<form action = "" method = "POST" enctype = "multipart/form-data"
id="formdata">
<input type = "file" name = "image" id="fileinput" />
<input type = "submit" name="upld" id="upldbtn" />
</form>
$("#formdata").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
I generated the next form in jQuery:
$('.content').append('
<form name="make_new_model_release" enctype="multipart/form-data">
<input data-validate="validate" type="text" name="new_model_release_title" placeholder="Enter new model release title" />
<input type="file" name="newModelReleaseFile" id="newModelReleaseFile" />
<input type="submit" value="Create new model release" />
</form>');
Server side simple:
var_dump($_FILES);
AJAX code:
var data = form.serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: formurl,
data: data,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data) {
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
after submitting the $_FILES array is empty.
I checked php.ini
file_uploads=On |
upload_max_filesize=128M | post_max_size=128M
Temp folder is allowed for read and write
I tried to make data: new FormData(formId) - nothing changed, $_FILES array is empty.
If you used jQuery('#dailyActivity').serialize(),
It it is not working for <input type'file'>
Have look at this jsFiddle Does not works
and this one .serialize()
Data from file select elements is not serialized.
Have look at this https://stackoverflow.com/a/8758614/3425489
In you case try this
To send <input type'file'> you may want to try this
var formData = new FormData($('form')[0]);
or specify exact data for formdata
var formData = new FormData();
// Append your other Data
formData.append('newModelReleaseFile', $('input[type=file]')[0].files[0]);
And you ajax call will be
$.ajax({
type: 'POST',
url: formurl,
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data){
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
I know how to upload images by ajax but I want to upload images via jQuery steps. I've tried multiple ways but its not not working. If anyone has ever done that please help me. Thanks.
HTML
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
jQuery
if(currentIndex == 0)
{
var upload_doc = $("#upload_doc").val();
event.preventDefault();
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : { upload_doc : upload_doc, step1 : step1},
success: function(response) {
console.log(response);
}
});
}
Follow this way for upload an image, In this way you don't want HTML form.
Add this code to your mainpage.php
<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery('#uploadImage').on("click", function (e) {
var uploadedFile = new FormData();
uploadedFile.append('upload_doc', upload_doc.files[0]);
jQuery.ajax({
url: 'lab1.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: uploadedFile
});
});
</script>
Then add this for upload.php
<?php
// check record array
print_r($_FILES);
move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
<form action="" name="imageUploadForm" id="imageUploadForm" method="post" enctype="multipart/form-data">
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
</form>
<script type="text/javascript">
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#upload_doc").on("change", function() {
$("#imageUploadForm").submit();
});
});
</script>
From your comment,
actually the thing is that I'm submitting many values also when uploading the image. so one click of next i sends so many data including image. rest data goes well except image only.
If you're uploading file, along with other input values, through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object, FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
So your jQuery should be like this:
if(currentIndex == 0){
event.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response) {
console.log(response);
}
});
}
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
I am uploading files to a server, my code is running perfectly but i want to show progress bar till the image is being uploaded, i have seen various tutorials in core php but i want to accomplish it in codeigniter framework.
Below is my code:
<form name="posting_comment" id="posting_comment_<?=$row1['id']?>">
<input type="file" name="save_movie_<?=$row1['id']?>" id="movie_<?=$row1['id']?>" />
<input type="button" class="postbtn" id="submit_movie_<?=$row1['id']?>" value="Upload Video File" onclick = "return sendCareerData(<?=$row1['id']?>)"/>
</form>
<script type="text/javascript">
function sendCareerData(a)
{
var data = new FormData(document.getElementById('posting_comment_'+a));
data.append("file_m_id", a);
$.ajax({
type:"POST",
url:"<?php echo site_url('Dashboard/do_upload');?>",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success:function(data)
{
console.log(data);
}
});
}
</script>
Controller:
public function do_upload()
{
$lecture_id=$_POST['file_m_id'];
$output_dir = "./uploads/";
$fileName = $_FILES["save_movie_".$lecture_id]["name"];
move_uploaded_file($_FILES["save_movie_".$lecture_id]["tmp_name"],$output_dir.$fileName);
}
Use this before your success function
<script type="text/javascript">
function sendCareerData(a)
{
var data = new FormData(document.getElementById('posting_comment_'+a));
data.append("file_m_id", a);
$.ajax({
type:"POST",
url:"<?php echo site_url('Dashboard/do_upload');?>",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$("#loading").html('Please wait....');
},
success:function(data)
{
console.log(data);
}
});
}
</script>
and in your view add
<div id="loading"></div>
Read this for more https://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684