I have two AJAX functions: one for an image file upload, one for a form info upload.
File Upload
function uploadFile(insertNodeID, inputFileID){
var img = document.getElementById(inputFileID).files[0];
var form_data = new FormData();
form_data.append('file[]', img, img.name);
var objXML = new XMLHttpRequest();
objXML.onprogress = updateProgress;
objXML.onload = function() {
if(objXML.readyState==4 && objXML.status==200) {
if(objXML.responseText !== 'no'){
document.getElementById(insertNodeID).src = objXML.responseText;
}
else{
errorInOut('There was a problem uploading the file.');
}
}
};
objXML.open('POST', baseURL+'ajax/admin_fileupload/', true);
objXML.send(form_data);
Form Info Upload
function uploadFormInfo(strURL, strData, type) {
strURL = baseURL+'ajax/'+strURL+'/';
var objXML = new XMLHttpRequest();
objXML.onreadystatechange = function() {
if (objXML.readyState == 4 && objXML.status == 200) {
returnXML(objXML.responseText, type);
}
};
objXML.open("POST", strURL, true);
objXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
objXML.send(strData);
They both work perfect independently.
The issue I'm running into is when I call the uploadFormInfo(), then call uploadFile(), the document.getElementById(insertNodeID).src does not render the uploaded image. It still uploads the image to the server and the responseText is the correct path to the image. I did a console.log on the .src of the id AFTER the I plugged in the new image and the .src is correct BUT, it never changes in the elements tab in Chome inspect. It also works fine BEFORE I call uploadFormInfo().
I've tried and number of things (sending a separate request header for the uploadFile) and nothing works.
I'm stumped.
Related
I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[‘quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});
Basically my problem is that i have a canvas and i want to use the canvas in a form like if it were an image submitted in a input with a type of file, so i can access the $_FILES array..
The project i have made is an image cropping script where a user chose an image file through input type file, and then the script draw the image onto a canvas, then the user can zoom/crop the image... that all works perfectly fine..
But how can i send the cropped image to a php file as form file input data and access the $_FILES super global array?
I really hope someone can help
This link here tries to do something similar to me but i dont understand how it works, or how i could do the same with my project?
Javascript
function convertCanvasToImage() {
var temp_ctx, temp_canvas;
temp_canvas = document.createElement('canvas');
temp_ctx = temp_canvas.getContext('2d');
temp_canvas.width = windowWidth;
temp_canvas.height = windowWidth;
temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);
var dataurl = temp_canvas.toDataURL("image/jpeg");
croppedImage.src = dataurl;
contentCall(dataurl);
}
function contentCall(profileImage) {
var http = new XMLHttpRequest();
var url = "ajax.php";
var params = "profileImage=" + profileImage;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
}
};
http.send(params);
}
document.getElementById("myfiles").addEventListener("change", pullFiles, false);
document.getElementById("scaleSlider").addEventListener("input", updateScale, false);
document.getElementById("convert").addEventListener("click", convertCanvasToImage, false);
UPDATE
I managed to solve the problem myself
var multiPart = new FormData();
var fileName = "pernille";
multiPart.append('retard', 'christian');
temp_canvas.toBlob(function(blob){
multiPart.append('blobTest', blob, fileName);
contentCall(multiPart);
}, "image/jpg");
}
function contentCall(profileImage) {
var http = new XMLHttpRequest();
var url = "ajax.php";
http.open("POST", url, true);
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
}
};
http.send(profileImage);
}
You'll need to store the canvas (as an image) in a hidden form field as its value and then when you submit your form, the image will be submitted.
// Save canvas as dataURL image
var dataURL = canvas.toDataURL('image/png');
I'm building a front-end interface for a back-end image edited process (don't know all the correct jargon).
Basically:
user should be able to upload an image file through the UI
which sends it to the server
where the image is edited in some way
then the UI should display the edited image
I'm using an XHR request with the POST method as shown below to send the image file to the server.
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
uploadButton.onclick = function() {
this.innerHTML = 'Uploading...';
//---------------
var files = fileSelect.files
var formData = new FormData();
var file = files[0]
if (file.type.match('image.*')) {
formData.append('photos[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', true);
xhr.onload = function() {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}; //end on-click 'Upload'
<input type="file" id="file-select" name="photos[]"/>
<button type="submit" id="upload-button">Upload</button>
My question is: In general, once the image file is sent to the server, by the code above, when/how does the edited image get sent back?
Will it be sent back as part of the server response to my POST request, and thus accessible in my processRequest callback function (assuming the server is configured to process it that way)?
Do I have to send a GET request to get the edited file?
I do not have access to the server/back-end at this point in time, and just know how the UI is supposed to work.
I am programming an embedded Device in C with a webserver. One Task is to download files from this devices. I want to Download serveral files at once, so i created an ajax-request, which using POST-Request and a bunch of filenames to return a zip-file (i create these zip-file on my own on the device). Everything works fine, but the dialog save as appears after the whole zip-file was transmitted.
At server-side the device is sending the 200 OK-, Content-Type: application/octet-stream- and Content-Disposition: attachment; filename="testzip.zip"-headers.
At client-side i using this javascript-code(got this from stackoverlfow: Handle file download from ajax post):
function downloadFiles(filenames) {
var xhr = new XMLHttpRequest();
xhr.open('POST', /file-save/, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
var filename = "test.zip";
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([this.response], { type: type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
};
xhr.send(filenames);
}
The if-statement if (this.status === 200) is reached, when the whole file is transmitted. If the size of the file is small, there is not a problem, because the user isn't recognizing the lack of time. But is the file about 50MB the user can't see any download although the file is downloading. In my opinion the reason is a.click(), because the click-method imitades the begin of the download.
Is there sombody who can help me out with a solution or some hints?
By the way, jquery isn't an option!.
Thanks for any help
EDIT: my goal is to download a file like on every webpage with large files, where i get a dialog with the location to save and i can see the download-progress.
SOLUTION(Hint from Herr Derb):
function downloadFiles(filenames) {
var xhr = new XMLHttpRequest();
xhr.open('POST', /file_save/, true);
xhr.onload = function () {
if (this.status === 200) {
var mydisp = xhr.getResponseHeader('Content-Disposition');
var save_response = xhr.responseText;
var var_json_format = JSON.parse(save_response);
/* check for errors */
if(var_json_format["error"]) {
return;
} else {
status = _.findWhere(var_json_format["link"], {id : 'status'}).value;
download_id = _.findWhere(var_json_format["link"], {id : 'download_id'}).value;
}
if(status != "active") {
return;
}
var filename = "test.zip";
var downloadUrl = "/file_save/" + download_id;
var a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
};
xhr.send(filenames);
return;
}
Your first request should only create the zip file on your server and return a link to reach it. After you received that link on the client site, simply execute it. This way, everything will happen as you desire, as it will be a regular file download.
And ss soon the download is finished, your free to delete the file again.
I want to make image upload from url for example: http://.. ../logo.png
I need to make formData object from image url but it doesn't work:
HTML:
<form id="form-url">
<input type="text" class="image" id="textarea" placeholder="URL" />
<button>UPLOAD</button>
</form>
Javascript:
$("#form-url").submit(function(e) {
if ($(".image").val() != "URL" && $(".image").val() != "") {
//I also tried this:
var data;
var img = new Image();
img.src = $(".image").val();
img.load = function(){
data = getBase64Image($(".image").val());
};
//but it send undefined
//and this:
var data = URL.createObjectURL($(".image").val()); //dont work
//error: TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL.
//Upload process working on normal input type file uploading but no on URL image
var formData = new FormData(data);
formData.append("fileToUpload", data);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_ajax.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
data = xhr.responseText;
datas = data.split("_");
if (datas[0] != "true") {
alert(data);
} else {
alert('YES');
}
} else {
alerter('An error occurred while uploading this file! Try it again.');
}
};
xhr.send(formData);
} else { alerter("Your file must be an image!"); }
return false;
});
My php script for debug:
<?php
if (isset($_POST)) {
var_dump($_POST);
if (empty($_FILES['fileToUpload']['tmp_name'])) {
echo "Your file must be an image!";
} else {
echo $_FILES['fileToUpload']['name'];
echo $_FILES['fileToUpload']['size'];
}
}
?>
Thanks for all help and your time..
and sorry for my bad english (student)
If getBase64Image is from here, or is similar to it.
Then you are using it wrong. You need to pass it the image node itself. Also the image onload event is async, and as such you have to wait for it to be done to get the data and send it.
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', "upload_ajax.php", true);
...
var img = new Image();
img.onload = function(){
var data = getBase64Image(this);
formData.append("fileToUpload", data);
xhr.send(formData);
};
Also note on the server side you will need to decode it from the base64 encoding, as it is being sent by string, it is going to be in $_POST not $_FILE
var rawContents = base64_decode($_POST['fileToUpload']);
Note you could also just send the url to the php script and just have php get the image data
var rawContents = file_get_contents($_POST['imageurl']);