How to send additional data in ajax request along with formData - javascript

I have a following ajax request onChange of file input value.
$(':file').change(function(){
var file = this.files[0];
var formData = new FormData($('form')[0]);
var id= $(this).attr('data-post-id'); // What I want to send additionaly to file
$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
data:{id:id}, // what is actually not working
cache: false,
contentType: false,
processData: false
});
});
I am adding an attribute to the html tag that includes an id that I wish to send along with file related data.
<input type="file" name="img" data-post-id="{{entity.id}}" />
I use PHP under Symfony2 like:
if ($request->isMethod('POST')) {
$image = $request->files->get('img');
}
I need an equivalent way to get also the id.

Pass it through url,
$(':file').change(function(){
var file = this.files[0];
var formData = new FormData($('form')[0]);
var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file
$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload?id="+id,
//...........................................................^....
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
Or you can use append method to add id
$(':file').change(function(){
var file = this.files[0];
var formData = new FormData($('form')[0]);
formData.append("id",id);
//...............^.......
var id= $(this).attr('data-post-id'); // What I want to send additionnaly to file
$.ajax({
url: "http://localhost/bghitn/web/app_dev.php/image/upload?",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});

Just try this,
data:{'id':id,
'formdata':formData,
},

You don't send data twice. Send inthis format :
data: {
formData : formData,
id:id
},

Related

Doing a request with text and file doesn't fill laravel filebag array

I'm trying to post an image and some text via ajax onto my laravel server except I can't seem to add the File into the ajax request.
I have tried making a FormData and appending the needed params, I also tried serializing my form with jQuery.
$("#create-post-button").click(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// var formData = new FormData();
// formData.append('src', $('#src')[0].files[0]);
// formData.append('title', $);
// formData.append('_token', CSRF_TOKEN);
// formData.append('_method', 'POST');
event.preventDefault();
console.log($('#src')[0].files[0]);
$.ajax({
headers: {
'X-CSRF-TOKEN': CSRF_TOKEN
},
url: '/posts/create',
type: 'POST',
data:
{
'_method': 'POST',
'_token': CSRF_TOKEN,
'title':$("#title").val(),
'src': {
'name':$('#src')[0].files[0].name,
'size':$('#src')[0].files[0].size
}
},
dataType: 'json'
});
});
I expect that when I dump my $request in laravel, that it has the correct request params but also including the $file (FileBag) param for the file that is being posted.
EDIT:
I have looked up the link #charlietfl provided in the comments and it helped me a lot, so here is the end result:
$("#create-post-button").click(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
var file_data = $('#src').prop('files')[0];
var form_data = new FormData();
form_data.append('_method', 'POST');
form_data.append('_token', CSRF_TOKEN);
form_data.append('title', $('#title').val());
form_data.append('src', file_data);
$.ajax({
url: '/posts/create',
dataType: 'text',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
showSuccessUploadingPost();
},
error: function() {
showErrorUploadingPost();
}
});
});
The CSRF token at file upload required to pass as a GET parameter.
$("#create-post-button").click(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var form_data = new FormData();
form_data.append('title', $('#title').val());
jQuery.each(jQuery('#src')[0].files, function(i, file) {
data.append('src', file); //use the following line to handle multiple files upload
// data.append('src' + i, file);
});
$.ajax({
url: '/posts/create?_token=' + CSRF_TOKEN,
data: form_data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(){
showSuccessUploadingPost();
},
error: function() {
showErrorUploadingPost();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form id="uploadFrm" enctype="multipart/form-data" method="post">
<input type="file" name="src" />
<button id="create-post-button">Upload</button>
</form>

Append additional variable to formData

How do I append dataid to the formData so that AJAX POST's both? I have tried formData.append('id', dataid); and formData = formData.append('id', dataid);
$(document).ready(function() {
$('#insert_screen').on("submit", function(event) {
var dataid = $("#res option:selected").attr('data-value');
console.log("Value", dataid);
event.preventDefault();
var form = $('form')[2];
var formData = new FormData(form);
$.ajax({
url: "insert_new_screen.php",
data: formData,
method: "POST",
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#insert').val("Inserting");
},
success: function(data) {
$('#add_screen_modal').modal('hide');
window.location.reload();
}
});
});
});
UPDATE:
Below is the code I managed to get working:
$(document).ready(function(){
$('#insert_screen').on("submit", function(event){
var dataid = $("#res option:selected").attr('data-value');
console.log("Value", dataid);
event.preventDefault();
var form = $('form')[2];
var formData = new FormData(form);
formData.append("RecordID", dataid);
$.ajax({
url:"insert_new_screen.php",
data: formData,
method:"POST",
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#add_screen_modal').modal('hide');
window.location.reload();
}
});
});
});
Many thanks to all those who gave me help. I hope this helps other.

How to add PHP Session variable into FormData using AJAX?

I'd like to pass a PHP session variable (called 'profileid') using FormData and AJAX. I thought this below would work, it did not. Why?
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
imageData.append('profileid', <?php echo $_SESSION['profileid'];?>);
//Make ajax call here:
$.ajax({
url: '/upload-image-results-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: imageData,
//leaving out the rest as it doesn't pertain
You could add the profileid in the $.ajax URL parameter instead of adding it in FormData:
$(document).ready(function (e) {
$('#uploadImageForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "/upload-image-results-ajax.php?profileid=<?= $_SESSION['profileid']; ?>",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}));
$('#uploadImage').on("change", function() {
$("#uploadImageForm").submit();
});
});
Don't forget to place session_start(); at the beginning of your code.

How to send String data with formdata in ajax

<script type="text/javascript">
$(document).ready(function(){
$("#btnUpdate").click(function(){
alert($("#frm_data").serialize());
var formData = new FormData($("#frm_data")[0]);
var Desc= CKEDITOR.instances.editor1.getData();
$("#btnUpdate").attr('value', 'Please Wait...');
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
$("#btnUpdate").attr('value', 'Update');
}
});
return false;
});
})
</script>
i use ckeditor for textarea field. but its can update value with new value, so i want to use another way with send textarea value with form data.
so how to send Desc data with fromData. in ajax.
To achieve this you can use the append() method of FormData to add whatever additional information you require:
$("#btnUpdate").click(function(e) {
e.preventDefault();
var $btn = $(this).attr('value', 'Please Wait...');
var formData = new FormData($("#frm_data")[0]);
formData.append('desc', CKEDITOR.instances.editor1.getData());
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'post',
success: function(response) {
$btn.attr('value', 'Update');
}
});
});

How to upload a file using jQuery.ajax and FormData

When I use XMLHttpRequest, a file is correctly uploaded using FormData. However, when I switch to jQuery.ajax, my code breaks.
This is the working original code:
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
Here is my unsuccessful jQuery.ajax attempt:
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xm = $.ajax({
url: "upload.php",
type: "POST",
data: fd,
});
}
What am I doing wrong? How can I get the file to be uploaded correctly, using AJAX?
You have to add processData:false,contentType:false to your method, so that jQuery does not alter the headers or data (which breaks your current code).
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
// .. do something
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
If you are uploading from a HTML5 form that includes an input fo type file you can just use querySelector and FormData and it works.
In case of php it will give you all files in the $_FILE and all other inputs in the $_POST array.
JS/jQuery:
function safeFormWithFile()
{
var fd = new FormData(document.querySelector('#myFormName'));
$.ajax({
url:'/catchFormData.php',
method:'POST',
data:fd,
processData: false,
contentType: false,
success:function(data){
console.log(data);
}
});
}
HTML:
<form id="myFormName">
<input id="myImage" name="myImage" type="file">
<input id="myCaption" name="myCaption" type="text">
</form>

Categories

Resources