Send a blob with ajax, don't work in my case - javascript

So, i have an image on my page with this for src attribut :
src="blob:47d2cdd6-0ff0-401f-a195-a671d0db9b05"
I need to send this blob to php with ajax, for save this blob (a gif in my case) on my server.
This is my ajax :
var data = new FormData();
data.append('file', $('myImage').attr('src'));
$.ajax({
type:"POST",
url: "/webcam/",
data: data,
contentType: false,
processData: false,
success: function () {
parent.$.fancybox.close();
},
error: function() {
alert("not so boa!");
}
});
But, when i am on my php script, i don't know how to use this blob... When i try readimageblob() from imagick for example, i have an error.
Am i in the good way ?

Related

Posting data with jQuery in Wordpress succeeds, but fails with FormData

I want to upload a file using jQuery/Ajax in my Wordpress plugin. The javascript to PHP call works. So the wiring etc. works. But as soon as I post the formData, necessary to post the files, I don't reach the PHP function any more.
The javascript,
var doesntWork = new FormData();
doesntWork.append('file', 'a name');
var withthisItWorks = 'text'
var data = {
'action': 'emfi_file_upload',
'data': doesntWork
}
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: data,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});
The PHP function just returns a string answer:
function emfi_file_upload_callback() {
echo 'Yes, in the callback';
wp_die();
}
When I put the plain text in my data object I get answer from the PHP function. When I put the formData in, there is no answer. I've tried a lot of examples on the internet, but it boils down to this every time. Adding contentType: false and processData: false, as was mentioned somewhere else, didn't help. What's wrong?
All fields that are being sent must be in the formdata object.
Additionally for FormData to work with jQuery.ajax, processData and contentType have to be set to false.
var doesWork = new FormData();
doesWork.append('file', someFile);
doesWork.append('action', 'emfi_file_upload');
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: doesWork,
contentType: false,
processData: false,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});

FormData in multiple ajax request files

I'm trying to do a Ajax's loops requests for send files to an API but i don't not what I send at Ajax's data. When I do only file in upload I use the own formdata object and works very well. I tried use loop and each row send an individual file but it's doesn't works too:
Multiple files:
var form_data = new FormData();
for(i=0;i<3;i++){ // 3 length just for tests
form_data.append('file', $('#myfile').prop('files')[i]);
}
for (var value of form_data.values()) {
$.ajax({
url: 'URI',
data: value,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert("Success!")
},
error: function(e){
alert("Error")
}
});
}

how to append formdata in ajax call with image in php?

I want to send FirstName, LastName and Image through Ajax Call to PHP. I am able to send the data without image, and I am able to send the image without text using formdata but the problem is I am not able to do both at a time. Kindly check my code what I am doing wrong:
<script>
function createBasicInfo() {
// For Image Send
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
// For Text Send
var data = {
'firstname' : jQuery('#firstname').val(),
'lastname' : jQuery('#lastname').val(),
};
**//Here Is the Problem, I am not able to append the data with Text**
formdata.append(data);
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
In above code if I comment
//formdata.append(data); // Then only image will send to php
And If I use in Ajax Call
data: data, // Then only FirstName & LastName will send to php without Image
I am not able to send text data and image both at the same time to php file.
Any idea or suggestion would be welcome.
You could just do this insted of formdata.append(data):
formdata.firstname = jQuery('#firstname').val();
formdata.lastname = jQuery('#lastname').val();
Just append your firstname and lastname into formdata. Then send full formdata.
<script>
function createBasicInfo() {
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
formdata.append('firstname', jQuery('#firstname').val());
formdata.append('lastname', jQuery('#lastname').val());
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
// ...
// ...
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>

Ajax send array and Image in same request

I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})

POST data using AJAX POST

Is it possible to post image file using the jQuery's ajax post method. Would it work if I just put the file data in the POST request's 'data' parameter?
I am using django framework. This is my first attempt:
$('#edit_user_image').change(function(){
var client = new XMLHttpRequest();
var file = document.getElementById("edit_user_image");
var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
/* Create a FormData instance */
var formData = new FormData();
formData.append("upload", file.files[0]);
client.open("post", "/upload-image/", true);
client.setRequestHeader("X-CSRFToken", csrftoken);
client.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=frontier");
client.send(formData); /* Send to server */
});
The problem with this is that I don't get the'request.FILES' object on the serer side in my 'views.py'.
I also tried doing it with ajax post but it doesn't work either.
$('#edit_user_image').change(function(){
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:document.getElementById("edit_user_image").files[0],}
$.post("/upload-image/", data, function(){
});
});
Edit from one of the answers:
$('#edit_user_image').change(function(){
var formData = new FormData($("#edit_user_image")[0]);
$.ajax({
type: "POST",
url: "/upload-image/",
xhr: function() { // custom xhr
// If you want to handling upload progress, modify below codes.
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
// Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr) {
// If you want to make it possible cancel upload, register cancel button handler.
$("#yourCancelButton").click(xhr.abort);
},
success: function( data ) {
// Something to do after upload success.
alert('File has been successfully uploaded.');
location.reload();
},
error : function(xhr, textStatus) {
// Something to do after upload failed.
alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
}
});
});
This is my final working solution:
$('#edit_user_image').change(function(){
var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
var formData = new FormData($("#edit_user_image")[0]);
var formData = new FormData();
formData.append("file", $('#edit_user_image')[0].files[0]);
formData.append("csrfmiddlewaretoken", csrftoken);
$.ajax({
type: "POST",
url: "/upload-image/",
data: formData,
contentType: false,
processData: false,
});
});
You can if you use FormData, otherwise you have to use Flash or iframes or Plugins (these ones use flash or iframes), FormData comes with HTML5 so it won't work in IE <= 9, a great guy created a replica of FormData for old browsers, to use it you only have to put formdata.js in the head tag. So in my opinion you have to use FormData.
We say you have a form like this:
<form method="POST" name="form" id="form" enctype="multipart/form-data">
<input type="file" id="img"/>
<input type="submit"/>
</form>
you have to get the img chosen by the user so your javascript have to look like this:
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var data = new FormData($('form').get(0));
$.ajax({
url: :"/URL",
method: "POST",
data: data,
success: function(data){},
error: function(data){},
processData: false,
contentType: false,
});
});
});
and now you are going to be able to retrieve the img chosen by the user in django with:
request.FILES
Yes. You can post your image file using jQuery's ajax.
Try below code snippet.
// Your image file input should be in "yourFormID" form.
var formData = new FormData($("#yourFormID")[0]);
$.ajax({
type: "POST",
url: "your_form_request_url",
xhr: function() { // custom xhr
// If you want to handling upload progress, modify below codes.
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
// Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr) {
// If you want to make it possible cancel upload, register cancel button handler.
$("#yourCancelButton").click(xhr.abort);
},
success: function( data ) {
// Something to do after upload success.
alert('File has been successfully uploaded.');
location.reload();
},
error : function(xhr, textStatus) {
// Something to do after upload failed.
alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
}
});
My suggestion is add "return false after the ajax block.

Categories

Resources