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
Related
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
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/
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);
}
I'm using ajax file upload javascript and php script to upload an image. It works satisfactorily with $_FILES but I need to send some additional data to the processing script. The form HTML looks like:
<form id="image1" action="" method="post" enctype="multipart/form-data">
<label>image 1?</label>
<p><input type="file" class="saveImage" name="image1" value="<?php echo $something; ?>" id="<?php echo $id; ?>" additional_info="some data" /></p>
<p> <input type="submit" value="Upload" class="submit" /></p>
</form>
I need to be able to pass a variable id and some other data, call it "additional_data" to the php script, then process it in my php script using $additional_data = $_POST['additional_data']. The javascript I'm using is:
<script>
$(document).ready(function (e) {
$("#image1").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var DATA=$(this).val();
var ID=$(this).attr('id');
var ADDL=$(this).attr('additional_data');
var dataString = 'image1='+DATA+'&id='+ID+'&additional_info='+ADDL;
$.ajax({
url: "uploadFile.php",
type: "POST",
// data: new FormData(this),
data: new FormData(this,dataString),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
It doesn't send the dataString, only the FILES array.
I also wanted to do the same thing.
Here's my solution :
The JS part :
var file_data = this.files[0];
file_data.name = idaviz +'.pdf';
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append('extraParam','value231');
console.log(file_data);
console.log('here');
var oReq = new XMLHttpRequest();
oReq.open("POST", "ajax_page.php", true);
oReq.onload = function (oEvent) {
if (oReq.status === 200) {
console.log('upload succes',oReq.responseText);
} else {
console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
}
};
oReq.send(form_data);
});
The PHP part:
echo $_REQUEST['extraParam']; //this will display "value231"
var_dump($_FILES['file']); //this will display the file object
Hope it helps.
Addition info about extra parameters on formData can be found
here!
I hope I understand you right. Maybe this snippet helps you:
var formData = new FormData();
formData.append("image1", fileInputElement.files[0]);
formData.append("ID", ID);
formData.append("ADDL", ADDL);
And then set this formData variable as data:
type: "POST",
data: formData,
contentType: false,
Hi I'm having some trouble figuring out whats wrong with my ajax request.
Its a script for uploading pictures.
The php file sets up a page with an inline popup for selecting images and displaying their previews
the selection is done in a form called #uploads and if the form is submitted it works the way its supposed to, refreshing to a page where the $_FILES info is included
the php file:
<?php
echo (print_r($_FILES));
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/style/style.css">
<title>test</title>
</head>
<body>
<div id="overlay"></div>
<div id="bilder"></div>
<div id="nybild">
<div id="ny_header">
<form id="upload" method="post" enctype="multipart/form-data">
<input type="file" id="filer" name="filer" multiple>
<input type="submit">
</form>
<div id="preview"></div>
</div>
<div>
<button id="add">Lägg till</button>
<button id="cancel">Avbryt</button>
</div>
</div>
<button id="lagg_till">Lägg till nu bild</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/js/page.js"></script>
</body>
</html>
';
echo $html;
The java script file contains the logic for showing selection popup, creating previews of files and finally uploading them with ajax. This last part however does not work. The page returned displays an empty $_FILES array
page.js:
$(function(){
$nybild = $("#nybild");
$overlay = $("#overlay");
$overlay2 = $("#overlay2");
$preview = $("#preview");
$("#lagg_till").click(function(){
$overlay.show();
$nybild.show();
});
$("#filer").on("change", function(){
$preview.html("");
var files = this.files;
for(var i = 0; i < files.length; i++){
if(files[i].type.match("image.*")){
var reader = new FileReader();
reader.onload = (function(theFile){
return function(e){
$preview.append(["<img src='", e.target.result, "' class='thumb' title='", escape(theFile.name), "'/>"].join(''));
};
})(files[i]);
reader.readAsDataURL(files[i]);
}
}
});
$("#cancel").click(close_nybild);
$("#add").click(function(){
var formdata = new FormData($("#upload").get());
$.ajax({
type: 'POST',
dataType: 'text',
beforeSend: function(){
console.log(formdata);
},
success: function(data){
var pop = window.open("", "MsgWindow", "width=200, height=100");
pop.document.write(data);
},
error: function(){
$overlay2.hide();
alert("Upload Misslyckades B(");
},
// Form data
data: formdata,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
})
});
function close_nybild(){
$overlay.hide();
$nybild.hide();
reset($nybild);
}
var reset = function(e){
e.wrap("<form>").closest('form').get(0).reset();
e.unwrap();
$preview.html("");
}
});
The majority of the code is shamelessly copied from here:
How can I upload files asynchronously?