Upload photo in background with ajax - javascript

So I'm a bit new to ajax, I just want to see if anyone can help me with this...
I have my main page. I'll just put the element I'm working with so I don't have to put the whole page.
<input type="file" id="myphoto" />
Then, instead of submitting it, what I want to do is run it through a javascript function with an ajax form in it like this
$.ajax({
type: "POST",
url: "myphppage.php",
"Whatever other code needed"
})
to upload the photo. Then, the form URL could be a php page that moves the photo to a different directory. I hope you know what I mean. Any help would be greatly appreciated...

first make a html file which select the file from anywhere, like
uplaod.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX UPLOAD</title>
</head>
<body>
<form enctype="multipart/form-data">
<input id="file" type="file" />
<input type="button" id="upload" value="Upload" />
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="upload.js"></script>
</html>
now, make js file like below,
upload.js
$(document).ready(function() {
$('#upload').on('click', function() {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
});
now, make a directory uploads and a php file which upload the file to upload directory
upload.php
<?php
if (0 < $_FILES['file']['error']) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo "success";
}

XHR2 AJAX request can submit binary data like images:
DEMO
However, changing the address bar (windows.location) will interrupt the upload as the new page is loaded. You can work around of this by loading pages via AJAX and using History API:
Demo1

Those who have the common sense and/or enough brain to avoid gayQuery...
function uploadFile(){
var form_data = new FormData();
var first_file = document.getElementById('your_input_element_which_type_is_file').files[0];
var link = 'file_upload.php'; /*or which ever you have, maybe add ?params=xxx&other_params=yyyy */
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var response = xmlhttp.responseText;
/* check your custom response here */
}
/* check other errors here too */
}
form_data.append('file', first_file);
xmlhttp.open('POST', link, true);
xmlhttp.send(form_data);
}

Related

What did I wrong be converting that jquery code to plain javascript (Upload binary file to embedded server)

I am currently trying to implement an over-the-air update for my micro controller. I found an example which I can use. The problem is I would like to use it without access to the internet. The problem it is written in jQuery and I did not work with jQuery so far. Using jQuery does not work with the project since it has no internet access.
jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form method="POST" action="#" enctype="multipart/form-data" id="upload_form">
<input type="file" name="update" />
<input type="submit" value="Update" />
</form>
<div id="prg">progress: 0%</div>
<script>
$("form").submit(function (e) {
e.preventDefault();
var form = $("#upload_form")[0];
var data = new FormData(form);
$.ajax({
url: "/update",
type: "POST",
data: data,
contentType: false,
processData: false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener(
"progress",
function (evt) {
if (evt.lengthComputable) {
var per = evt.loaded / evt.total;
$("#prg").html("progress: " + Math.round(per * 100) + "%");
}
},
false
);
return xhr;
},
success: function (d, s) {
console.log("success!");
},
error: function (a, b, c) {},
});
});
</script>
";
And I tried to get the upload part with that but it seems I missing some properties or did set wrong parameters
Plain javascript:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Upload</title>
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", document.getElementById('fileupload').files[0]);
await fetch("/upload", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
body: formData, // body data type must match "Content-Type" header
});
alert("The file has been uploaded successfully.");
}
</script>
</head>
<body>
<p>Click on the "Choose File" button to upload a file:</p>
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()">Upload</button>
</body>
</html>
I would like to upload the new firmware which is a .bin file does that require some special settings?
I am using this the code for that example (c++): https://github.com/espressif/arduino-esp32/blob/master/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino
I modified it a little bit so it can be used in the access point mode.
I Can post the modified code too but since it does not work with html code there should be no error since it works with the jQuery code.
(I posted that code here too if it is really needed: https://forum.arduino.cc/t/why-can-i-do-not-perform-an-ota-update-when-i-am-in-the-ap-mode-it/952874/3)
jQuery request console output
JavaScript request console output
This is where the website code gets replaced

Ajax file upload not being store in the directory

I'm in the process of building a function in uploading a file(CSV) using AJAX. This is just a rough code since that I'm working and currently following a tutorial. I'm using XAMPP for server side languages
After executing i'm getting an alert that displays (obect FormData) inside and aside from that, the uploads directory is empty after submitting the file. Project currently has three items. (Uploads Folder, index.php and upload.php)
HTML
<form method="post" enctype="multipart/form-data">
<input id="file-uploading" type="file" name="fileUploading" />
<button id="upload" value="upload">Upload</button>
</form>
JAVASCRIPT
$('#upload').on('click', function() {
var file_data = $('#file-uploading').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
console.log('success');
}
});
});
PHP
<!doctype html>
<html>
<body>
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error' . $_FILES['file']['error'] . '<br/>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
</body>
</html>
I test successful.I think "uploads" permissions is not right.You should do:
sudo chown -R www-data:www-data uploads
I think you are missing out on enctype attribute on form.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
<form method="post" enctype="multipart/form-data">
// your content
</form>
Hope this helps..

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

jQuery file Upload and ajax

So, I have the following form and js/php:
php
<form enctype="multipart/form-data">
<input id="fileupload" type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/>
<input type="button" class="submit_form" value="submit">
</form>
<?php
add_action( 'wp_ajax_UploadImage', 'UploadImage' );
function UploadImage()
{
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
//Some function
}
?>
JS
function UploadImage(e)
{
jQuery('#fileupload').fileupload({
url: upload_image.ajax_url,
});
if(jQuery('#fileupload')) {
var form = document.forms.namedItem("upload_video");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
jQuery.ajax({
success : function(data){
alert('sddsf');
}
})
}
};
As you can see from here, when an image is selected using Blueimp jQuery File upload (which the js is not properly written), I want the image file to be handled by the php function.
In other words, the js is not correctly written and I am not sure how to initiate the plugin then when the image is selected, it is processed by the php function via ajax (meaning, how do I parse the file info to php function via ajax?)
Don't use $.ajax directly. The plugin already does that behind the scenes.
Here's a working example, based on your code, but adapted to run on JSFiddle:
$(document).ready(function(){
var url = '/echo/json/';
var formdata = {json: JSON.stringify({field1: 'value1'})};
jQuery('#fileupload').fileupload({
url: url,
formData : formdata,
dataType: 'json',
type: "POST",
contentType:false,
processData:false,
success : function(data){
alert('success...');
console.dir(data);
}
});
});
Demo: http://jsfiddle.net/pottersky/8usb1sn3/3/

Uploading multiple files with Ajax not making POST

I took an example of How can I upload files asynchronously? which is a great example BTW.
For some reason my POST is not making it to my php file. Even when I print_r($_POST) the array comes up blank. I am trying to pass 2 fields with this Script.
If I simple do an echo "test"; on my php file it will return that string.
I also tried var formData = new FormData($('form').serialize());
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'inserttest.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
success: function(data) {
alert(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
</script>
</head>
<form enctype="multipart/form-data">
<input type="text" name="words" id="words" />
<input name="file" type="file" id="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
Took it a step further and made it the long way with formData...still no luck
var words = $('#words').attr('value');
var file = $('#file').attr('value');
var formData = new FormData();
formData.append("words", words);
formData.append("file", file);
inserttest.php
Tried
<?php
echo print_r($_POST);
?>
and
<?php
echo print_r($_FILES);
?>
the Jquery version you're using is outdated and doesn't support this feature!
Change version 1.3.0:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
...to version 1.9.1:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
...and it works!! :D

Categories

Resources