Can't Upload Image via AJAX with Additional Parameters Because processData: false - javascript

I am trying to upload an image using ajax using the following code:
function saveToServer(file) {
const fd = new FormData();
fd.append('image', file);
$.ajax({
method: 'post',
data: {
image: fd,
diaryHash: "{{ $diary->hash }}",
entryHash: "{{ $entry->hash }}",
},
processData: false,
contentType: false,
url: "{{ action('EntriesController#storeImage') }}",
success: function(data, textStatus, jqXHR){
const url = JSON.parse(xhr.responseText).data;
insertToEditor(url);
}
});
}
I am passing the image to be stored and I am passing two other variables, diaryHash and entryHash.
I am not getting my passed variables in my controller because processData is set to false.
How do I pass data along with an image when doing an image upload with AJAX?

The issue is because you're placing the FormData object in the object to be serialised. You need to invert that logic and place the additional parameter inside the FormData, like this:
function saveToServer(file) {
const fd = new FormData();
fd.append('image', file);
fd.append('diaryHash', '{{ $diary->hash }}');
fd.append('entryHash', '{{ $entry->hash }}');
$.ajax({
method: 'post',
data: fd,
processData: false,
contentType: false,
dataType: 'json',
url: "{{ action('EntriesController#storeImage') }}",
success: function(data, textStatus, jqXHR){
const url = data.data;
insertToEditor(url);
}
});
}
Also note that I added the dataType property to the request so that jQuery will automatically deserialise the response for you.

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>

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.

Transmitting Form Data via Json

I believe I am making a very basic mistake somewhere.
I have a Form I want to transmit to a PHP page. I also want to send a parameter with that information so I have created a basic 2D array:
$fd['api'] -> contaning the parameter as a string
$fd['body'] -> containing the form data
I am struggling to transmit this array "$fd" as a json string and believe I am using the javascript syntax incorrectly somewhere as I do not often use Javascript.
Any Help would be appreciated.
function admin_statistics_form_send(){
var fd = []
fd['api'] = "refresh_all"
fd['body'] = new FormData(document.getElementById("admin_statistics_form"))
var jsonstring = fd
console.log(jsonstring)
$.ajax({
async: true,
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: jsonstring,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}
You only want to send the FormData object. To add other key/value pairs you append to that object:
function admin_statistics_form_send(){
var fd = new FormData($("#admin_statistics_form")[0]);
fd.append('api',"refresh_all");
$.ajax({
//async: true, // redundant since it is default and should never use `false`
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: fd,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}

Post array using formData

I am trying to add images, few string information and array using formData. I can successfully add images, string but can't add array information while adding. It always passes array as a string.Any help would be appreciated. My code
var reader = new FileReader();
var form_data = new FormData();
form_data.append('departure_city',departure_city);
form_data.append('inclusion_icons', inc_icons);
form_data.append('theme_icons',theme_icons);
$.ajax({
url: url,
type: "POST",
async: false,
cache: false,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
data: form_data,
}).done(function (data) {
console.log("Success");
console.log(data);
}).fail(function (data) {
console.log("Error");
console.log(data);
});
inclusion_icons and theme_icons are arrayz, however I'm getting them as a string.

Adding Accept header 'text/xml' in JQuery ajax file upload

How do I add an accept header 'text/xml' in JQuery ajax file upload?
It will upload a PDF file.
Here is the code I am using:
var fd = new FormData(document.getElementById('file'));
$.ajax({
url: '/myurlhere',
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(response) {
console.log('success... '+response);
}
}).fail(function(xhr,status,error) {
console.log(error);
});
The server expects the accept header to be xml, so causes a 406 error.
I have tried using dataType: 'xml' or header { Accept: 'text/xml' } and it causes a 400 error.
You have to set your contentType to "text/xml".
Change your call like this:
var fd = new FormData(document.getElementById('file'));
$.ajax({
url: '/myurlhere',
type: 'POST',
data: fd,
cache: false,
contentType: "text/xml",
dataType: "text",
processData: false,
success: function(response) {
console.log('success... '+response);
}
}).fail(function(xhr,status,error) {
console.log(error);
});
see this SO answer it may help
jQuery ajax post to web service

Categories

Resources