I was getting undefined file as an error in my php while uploading a file.
function click_submit_form() {
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data: $('#id_frm_charity_details').serialize(),
success: function (data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data'>
<input id="id_file" name="file" class="input-file" type="file"> <a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
In my php
<?php
$files = $_FILES['file']['name'];
$files_tmp = $_FILES['file']['tmp_name'];
$copy = copy($files_tmp, $files);
//echo $_POST['file'];
move_uploaded_file($files_tmp, "C:\wamp32\www\jb_from_live\src\uploaded_files/" . $files);
?>
If i use the above line then it says undefined index 'file'.But the execution not going after $files=$_FILES['file']['name'];
It says undefined index file.
Send image to this format
$('#form').submit(function() {
var img=$('#image').val();
var forms=($(this).serialize());
$.ajax({
type:"POST",
url: "do.php?do=upload",
data:forms+'&r='+encodeURIComponent(img),
success: function(result){ //your code }
});
Try this in your code like this
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function click_submit_form(){
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
var img=$('#id_file').val();
var forms=($('#id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data:forms+'&r='+encodeURIComponent(img),
// data: $('#id_frm_charity_details').serialize(),
success: function(data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
</script>
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data' >
<input id="id_file" name="file" class="input-file" type="file">
<a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
I recommend you to use FormData instead of serialize(). The advantage of using formData is that you can also upload pdf,xml,JSON files by specifying their content-type.
For eg:
var fData = new FormData();
fData.append("XML", new Blob([ xml ], { type: "text/xml" });
fData.append("JSON", new Blob([ JSON.stringify(json) ], { type: "application/json" }));
fData.append("PDF", file);
Make sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You cannot upload a file via ajax that simply unfortunately, for security reasons js doesn't have access to file data and therefore cannot post it via the form serialize function.
If you want to validate other parts of the form and then submit you could write a function like this
function submit(){
var valid = true;
//TODO: check validation on form, set valid to false if incorrect
if( valid )
document.forms[0].submit();
return false;
}
If you want to use HTML5 have a geez at this answer which utilizes the FormData() function:
How can I upload files asynchronously?
Otherwise if you with to upload a file asynchronously you'll have to look for a jsp or flash fallback plugin.
Here's a really good one:
http://blueimp.github.io/jQuery-File-Upload/
Related
I am trying to use dropzone to upload an image, and pass the folder to upload the image to.
My html form:
<form action="upload.php" class="dropzone" id="dropzoneFrom"></form>
<br>
<div align="center">
<button type="button" class="btn btn-info" id="submit-all">Upload</button>
My JS Script:
$(document).ready(function(){
Dropzone.options.dropzoneFrom = {
autoProcessQueue: false,
acceptedFiles:".png,.jpg,.gif,.bmp,.jpeg",
// Initiate the button
init: function(){
var submitButton = document.querySelector('#submit-all');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.on("sending", function(file, xhr, formData) {
formData.append("folder", "04"); // Append the folder to upload to.
});
myDropzone.processQueue();
});
this.on("complete", function(){
if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
});
},
};
I am appending the additional folder to upload to like this:
myDropzone.on("sending", function(file, xhr, formData) {
formData.append("folder", "04"); // Append the folder to upload to.
});
But in my upload.php page, how do I receive this information? I am currently receive the file and processing it like this:
if(!empty($_FILES)){
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
}
I found this page which gives a really good modelled example showing that you simply use the $_POST['folder'] request:
https://gist.github.com/kreativan/83febc214d923eea34cc6f557e89f26c
I am trying to send form variables to PHP via AJAX and show the result in console.log. But the console shows always no value for data. I don´t know what's wrong. What I have so far:
Part of jQuery Code:
...
init: function() {
this.on('success', function(csvFile, json) {
// AJAX
$.ajax({
url : "tests.php",
type : "POST",
data : this.csvFile
}).done(function (data) {
// Bei Erfolg
console.log("Erfolgreich:" + data);
}).fail(function() {
// Bei Fehler
console.log("Fehler!");
}).always(function() {
// Immer
console.log("Beendet!");
});
});
Part of HTML Code:
<form action="tests.php" class="dropzone" id="myAwesomeDropzone">
<input type="text" name="testname" value="das bin ich"/>
</form>
PHP Code:
if(!empty($_FILES)){
$test = $_FILES['file']['tmp_name'];
echo test;
}
if(!empty($_POST)){
$test2 = $_POST['testname'];
echo $test2;
}
Your HTML code and PHP works fine (just need to fix "echo test" to "echo $test" in your tests.php). Dropzone automatically attach itself to anything with class "dropzone" and it will do ajax requests to your server after you select a file.
If you want to programmatically:
HTML
<div id="myDZ">
Drop your file
<input type="text" id="testname" name="testname" value="hello_world"/>
<button id="upload">upload</button>
</div>
jQuery:
<script type="text/javascript">
$("#upload").click(function(e){
myDZ.processQueue();
})
var myDZ = new Dropzone("#myDZ", {
url: "tests.php",
autoProcessQueue: false,
init: function(){
this.on('sending', function(xhr, fd1, fd2){
//append extra data here
fd2.append("testname", $("#testname").val());
});
this.on('success', function(file, responseText){
//do after successful upload
console.log(responseText);
})
}
});
</script>
you can remove "autoProcessQueue: false" and remove the button stuff if you want it to auto upload once a file is selected.
more events can be found here: http://www.dropzonejs.com/#event-list
I am trying to use jquery( v. 1.11.3 )ajax, in conjunction with jquery.validate 1.15 to upload a form that includes input type file. You can see from the js comment lines some of everything I have tried. With each of the variations the php script returns "no image file". Of course, if I remove the jquery script, the form submits fine with accompanying page refresh. I really wanted to eliminate the page refresh for a better UX but I am having no luck getting this to work. If someone could help me fix my code, I'd really appreciate it. Please Note: I have researched numerous examples of jquery ajax .post but these examples are not helping me as those code structures don't work with Jquery.Validate plugin. I also found this answer here: File Upload PHP AJAX but as you can see from my code comments, I have tired this with no luck.
I must be missing something.
Heading ##The html and js:
<!DOCTYPE html>
<html>
<body>
<form action="imguploadTest.php" method="post" enctype="multipart/form-data" id="addItemsForm" name="addItemsForm">
<label>Select image to upload:</label>
<input type="file" name="itemImg" id="itemImg" />
<label>Name</label>
<input type="text" name="itemName" class="form-control" placeholder="Item Name..." maxlength="25" value="Really Cool Hoodie" />
<input type="submit" value="Upload Form" name="submit">
<div>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if (element.parent('.radio-inline').length || element.parent('.checkbox-inline') ) {
error.insertAfter(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});
$('#addItemsForm').validate({ // initialize the plugin
debug: true,
submitHandler: function(){
//var formData = $('#addItemsForm').serialize();
//var data = new FormData($('#addItemsForm'));
//var form = $('form')[0];
//var formData = new FormData(form);
//console.log(addform);
var frmData = new FormData($(this)[0]);
$.ajax({
url: "imgUploadTest.php",
data: frmData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done( function(res, jqXHR, textStatus) {
console.log(res);
//$('#results').html('<h4>Thumb link: ' + res["thumb"] + '<h4>');
//$('#results').append('<h4>Small link: ' + res["small"] + '<h4>');
//$('#results').append('<h4>Name: ' + res["name"] + '<h4>');
})
.fail( function (res, jqXHR, textStatus, errorThrown){
alert("failed! " + jqXHR, textStatus);
});
return false;
} // submitHandler
}); // validate
}); // doc ready
</script>
</body>
</html>
Heading ##The PHP:
<?php
include 'imguploader.class.php';
// FUNCTIONS
function imagehandler($item_attr_ID) {
$imgId = $item_attr_ID;
$img = new imgUploader($_FILES['itemImg']);
$time = time();
$thumb = $img->upload('mobileApp/uploads/', $imgId.'_thumb', 100,100); // change these numbers for display
$small = $img->upload('mobileApp/uploads/', $imgId.'_small', 400,400); // change these numbers for display
//$full = $img->upload_unscaled('mobileApp/uploads/', $time);
if($thumb && $small){ // && $full
return array($thumb, $small);
/* TO SHOW IMAGE
echo '<img src="'.$thumb.'" alt="aPicture" /> <img src="'.$small.'" alt="aPicture" /> <img src="'.$full.'"alt="aPicture" />';
*/
} else {
echo ( 'ERROR! '.$img->getError() ); // --> error code 011.1
}
} // end imagehandler()
// Processes
if (!empty( $_FILES["itemImg"]) ){
$item_attr_ID = "jPlayerandtheGirls_8_1456";
list($item_img_thumb, $item_img_small) = imagehandler($item_attr_ID);
if ($item_img_thumb && $item_img_small){
$r["thumb"] = $item_img_thumb;
$r["small"] = $item_img_small;
} else {
$r["thumb"] = "No Thumb";
$r["small"] = "No Small";
$r["name"] = "Didn't get to name";
echo json_encode($r);
}
} else {
$r = "No image file";
echo json_encode($r);
}
if (!empty( $_POST["itemName"] )){
$r["name"] = $_POST["itemName"];
json_encode($r);
}
?>
Ok I am able to answer my own question, though I am not exactly sure about the theory that goes with it as I am relatively new to JS/Jquery. .serialize() does not work. I think this is because by definition, files are binaries and thus can not be serialized - but don't quote me. So you have to use FormData to send the file. I was aware of this but could not come up with the proper syntax for use with jquery validation 1.15. See the answer below. Hope it helps someone to save some time.
first correct the rookie mistake with my code: add type: 'post'
second: the variable to hold your form's data, including the input type="file" is this var formData = new FormData($('#useYourFormElementIdHere')[0]);
So the final is this:
$.ajax({
type: "POST",
url: "imgUploadTest.php",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
}).done({}).fail({}).always({})
I'm maiking simple form with image upload option. I have problem with getting access to my uploaded file through jQuery in my PHP code.
How I can check uploaded file name, size in PHP?
HTML:
<form id="conversion_form" method="post" action="#" enctype="multipart/form-data">
<input type="text" id="prize_name" size="25" value="">
<textarea rows="8" cols="75" name="lista_losowanie" id="lista_losowanie">
<input id="file_img" type="file" name="image">
<div id="uploadPreview"></div>
</div>
<p><input id="button_draw" class="btn btn-lg btn-success" type="submit" value="Losowanie" /></p>
</form>
This is my Ajax, sending prize_name works good, but I have problem with my uploaded image. How I can send it in Ajax and receive in my PHP?
AJAX:
$('#button_draw').click(function(e) {
e.preventDefault();
var formData = new FormData();
// let's just take the first image
var file = $('#file_img')[0].files[0];
// but you also need to add the other fields to formData
var lista = $(this).closest('form').find('#lista_losowanie').val();
var prize_name = $(this).closest('form').find('#prizename').val();
formData.append('prize_img', file);
formData.append('lista', lista);
formData.append('prize_name', prize_name);
console.log(formData);
alert (formData);
$.ajax({
context: this,
url: './inc/new_draw.php',
data: formData,
type: 'POST',
success: function(response){
//odpowiedź serwera
//Trzeba sparsować zwrot
var json = JSON.parse(response);
if(json.odp == 1){
}
if(response == 2){
}
},
error: function(x,n,o){
}
});
});
PHP:
<?php
include ("config.php");
$prize_name = mysqli_real_escape_string($con, $prize_name);
$prize_img = mysqli_real_escape_string($con, $prize_img);
//HOW I CAN GET ACCESS TO UPLOADED IMAGE? HOW I CAN CHECK FILE SIZE ETC. THIS BELOW DOESNT WORK.
$file_size = $prize_img['size'];
$file_name = $prize_img['name'];
$file_type = $prize_img['type'];
echo $file_size;
if ($prize_name == NULL) {
$problem = TRUE;
$problem_code = 1;
echo json_encode($dodano);
}
?>
The Ajax method does support file upload, but only in newer browsers. For that you could use the XmlHttpRequest2 object and in your case ideally with a FormData object which will contain all the data (+ image) you want to submit, see this Article.
If you want to go with this, you can get the file via the HTML5 File API, quick example:
var formData = new FormData();
// let's just take the first image
var file = $('#fileinput').files[0];
// but you also need to add the other fields to formData
var lista = $(this).closest('form').find('#lista_losowanie').val();
var prize_name = $(this).closest('form').find('#prizename').val();
formData.append('prize_img', file);
formData.append('lista', lista);
formData.append('prize_name', prize_name);
// now you pass the formData object as data
$.ajax({
context: this,
url: './inc/new_draw.php',
data: formData,
// ....
});
As you can see, files is an array - so if you would use multiple select on your file input field, you could simply iterate through that array to get all selected images.
On the PHP side, if you use FormData, you will need to use the $_FILES array. See here: PHP $_FILES array.
From my example above, you would access the array like this (also added extension):
$size = $_FILES['prize_img']['size']
$name = $_FILES['prize_img']['name']
$type = $_FILES['prize_img']['type']
$extension = pathinfo($name, PATHINFO_EXTENSION);
With the XHR2 you could also do cool stuff such as tracking the progress of your uploaded file (progress bar). If you need compatibility for older browsers, there is an approach using iframes: example.
I have form like this:
<form class="wrefresh" action="Code Files/Accused.php" method="post" enctype="multipart/form-data">
<div class="row-form">
<div class="span3" style="margin-top: 06px">Picture:</div>
<div id="photo_settings2" style="margin-left:11px;">
<img id="Picture2" src="../../img/User No-Frame.png"/>
</div>
<div id='Upload_Panel'>
<input name="file" type='file' id='file_browse' onchange="readURL(this,'Picture2')" style="cursor: pointer;"/>
</div>
</div>
<button type="submit" class="a-btn2"style="cursor: pointer; background-color:#5C635F; color:white; font-family:'Candara'; margin-top:-47px; margin-left:192px; height:37px;"><big>Submit</big></button>
</form>
I have a php code in Accused.php:
$Mother_Language = $_POST['mlang'];
$Other_Languages = $_POST['olang'];
$Complexion = $_POST['comp'];
$Previous_Thug_Record = $_POST['precord'];
$Religion = $_POST['religion'];
$Type_of_Accused = $_POST['taccused'];
$City = $_POST['city'];
$Country = $_POST['country'];
$Nationality = $_POST['nationality'];
$ID_Mark = $_POST['idmark'];
$Hair_Color = $_POST['haircolor'];
$Occupation = $_POST['occupation'];
$Academic_Info = $_POST['ainfo'];
$Alias = $_POST['alias'];
$Caste = $_POST['caste'];
$Sect = $_POST['sect'];
$Remarks = $_POST['remarks'];
$photo = $_POST['file']; // giving error : undefined index/ getting nothing from the form.
my ajax function is:
<script>
var frm = $('.wrefresh');
frm.submit(function (ev)
{
ev.preventDefault();
var postdate = $(this).serialize();
var path = $(this).attr("action");
var mehtodtype = $(this).attr("method").toUpperCase();
$(".loadingimg").show();
$.ajax
({
type: mehtodtype,
url: path,
data: postdate,
success: function(data)
{
// Get Form Data.
$("#FIRtable").html(data);
$("#Accusedtable").html(data);
// Clear fields data.
$('form :input[type=text], textarea').attr('value', '');
// show hide icons when click on submit.
$(".loadingimg").delay(1000).fadeOut();
setTimeout(function()
{
$(".okicon").fadeIn('slow');
$(".okicon").delay(2800).fadeOut();
}, 1800);
}
});
});
</script>
I think my error is because of the ajax function i am using. I am getting every thing working except $photo = $_POST['file']; this // giving error : undefined index. help would be appreciated.
Uploading files through AJAX is a lot more complex than just referencing the $_FILES array. You'll need something like this to handle the file upload:
function upload_file() {
var formData = new FormData( document.getElementById( "form-uploader" ));
$.ajax( {
url : "Code Files/Accused.php",
type : "post",
xhr : function() {
my_xhr = $.ajaxSettings.xhr();
if( my_xhr.upload ) {
my_xhr.upload.addEventListener( "progress", handler_progress, false );
}
return my_xhr;
},
beforeSend : handler_before_send,
success : handler_complete,
error : handler_error,
data : formData,
contentType : false,
processData : false
} );
}
The primary difference between this and your code is that it employes the JavaScript FormData object, which is required to upload files with AJAX.
And then a variety of supporting functions that will be called when the upload starts, what its progress is, if there are any errors, and when it completes:
function handler_progress( e ) {
if( e.lengthComputable ) {
$( "progress" ).attr( {value:e.loaded, max:e.total} );
}
}
function handler_before_send( e ) {
var progress = $( "<progress></progress>" ).attr( "id", "progress-bar" );
$( "#form-uploader" ).append( progress );
}
function handler_error( e ) {
alert( "error" + e );
}
function handler_complete( e ) {
// The browser has completed the upload, do any clean-up here
}
This is mostly copy-and-paste from one of my projects where I do what you're describing (with a couple of changes to tie it in with your code), so you'll see some elements referenced by ID that are in my HTML that you'll have to modify. But this is essentially what you're looking for to upload files via AJAX.