I'm using an ajax call to upload a file, handled by PHP. The file should be placed in a specific directory based on a jquery variable. I can get the file to upload, but cannot pass the variable along with the file. PHP reports an undefined index error.
Ajax code:
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
I tried changing the data property to "fd+'&myVar='+myVar, however PHP cannot parse the data correctly and returns undefined index error for both the $_FILES['file'] variable as well as the $_POST['myVar'] variable.
How can I send both the file and a variable?
If you need another form field, call fd.append a second time:
fd.append('file', document.getElementById('select').files[0]);
fd.append('myVar',myVar);
You can append values other than files to a formdata object.
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
fd.append( 'myVar', myVar);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
Refer to $.ajax jQuery API Documentation.
It is clearly stated that data should be an object with key-value pairs representing data accepted by server-side script. Whatever, not sure why jQuery seems to not accept your data. Maybe you should try this out manually.
Since your test.php accepts POST data as myVar your jQuery Ajax configuration should probably look like
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myVar: document.getElementById('select').files[0]
},
success: function(e){
// some code here
}
});
Related
I'm trying to submit form by using formdata(). I need to get all data into json format, but due to file attachment i'm unable to do this in JSON.
Source Code:
<script>
$(document).on('submit', '.career', function(e){e.preventDefault();
var formData = new FormData();
formData.append("username", "test");
formData.append("acct", 23323);
var data = JSON.stringify(formData);
$.ajax({
method: "POST",
url: ajax.asyncUrl,
processData: false,
data: formData
})
.done(ajax.callbacks.submitAp);
Can any one please help me out about this issue.
Thanks in advance
You cannot JSON encode the binary data within a FormData object. To send FormData you need to supply it to the data property of the settings object in $.ajax(), and also set both contentType and processData to false. Try this:
$(document).on('submit', '.career-form', function(e) {
e.preventDefault();
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
// add file data here...
$.ajax({
method: "POST",
url: ajax.asyncUrl,
processData: false,
contentType: false,
data: formData,
}).done(ajax.callbacks.submitCareerApplicationLite);
});
I am trying to pass some HTML form data as well as a global array to PHP via AJAX. I know how to pass an array, and I know how to pass serialized form data. But how do I pass both at the same time? I have tried data: { formData, arrGFormId: arrGFormId }, but it doesn't work.
Edit: The form is just a simple HTML form with some inputs. My array values come from another AJAX call and are pushed into the global array arrGFormId.
function validateForm3(){
jQuery.ajax({
type: "POST",
url: "community_form_add.php",
async: false,
data: { arrAdminList: arrAdminList },
}).done(function(rs){
var sResult = rs.sResult;
var arrFormId = rs.arrFormId;
Array.prototype.push.apply(arrGFormId, arrFormId);
})
})
var arrGFormId = [];
jQuery('#formCreateForm').submit(function(e){
e.preventDefault();
var formData = new FormData(jQuery(this)[0]);
formData.append('sAction', 'submitForm');
jQuery.ajax({
type: "POST",
url: 'community_form_add.php',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
jQuery('.load_ball').css("display","block");
},
success: function(data)
{
jQuery('.load_ball').css("display","none");
jQuery('.cover').css("display","block");
jQuery('.popUpSubmitSuccess').fadeIn(300);
}
})
});
You need to encode the array, then you can add it to the FormData. You can convert it to JSON.
formData.append('arrGFormId', JSON.stringify(arrGFormId));
Then in PHP you can use json_decode($_POST['arrGFormId']).
you can use hidden input inside the existing form. the value of the hidden inputs are the array. so you only pass formData through ajax.
I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});
I'm trying to do a file upload through ajax and php. The PHP works fine when called directly, but each time I call it through ajax it is failing. I'm not getting any errors (annoying) it just does not want to upload.
My JQUERY looks like
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
form_data.file = file_data;
console.log(form_data);
var fileType = $(this).parent().find('input[type="hidden"]').val()
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
fileType:fileType,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
and my PHP looks like
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
print_r($_FILES[file_up]);
if ($_FILES[file_up][size]>250000){$msg=$msg."Your uploaded file size is more than 250KB
so please reduce the file size and then upload.<BR>";
$file_upload="false";}
$file_name=$_FILES[file_up][name];
$add="medicalPaperwork/$file_name"; // the path with the file name where the file will be stored
if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
echo "Thank god!";
}else{echo "Fuck you.";}
}else{
echo $msg;
}
What am I doing wrong? I'm going crazy trying to figure this out.
edit: the content of the form_data
You are using FormData incorrectly, use append to set the fields you want to upload
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
var fileType = $(this).parent().find('input[type="hidden"]').val()
form_data.append('file_up', file_data);
form_data.append('fileType', fileType);
console.log(form_data);
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
I'm testing out sending a formData object to PHP (I am following http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/), but am having some difficulty getting it off the ground. First, the formData object is created and populated with:
var formdata = new FormData();
formdata.append('my_key','my_value');
Then my ajax call with jQuery is:
$.ajax({
url: 'php_upload.php',
type: 'POST',
cache: false,
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
}
});
With the php_upload.php file containing:
<?php
echo $_FILES['my_key']['name'];
?>
But I get an undefined index: my_key error in the console.
Anyone have any idea what I might be doing wrong? Been scratching my head for ages.
You haven't added any files to the FormData, just a string which can be accessed by $_POST['my_key'].
To pass a file the second parameter of FormData.append has to be a FILE or a BLOB.