Ajax uploads not working - javascript

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?

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

How to upload multiple image upload without submit button using ajax jquery?

How to upload multiple image upload without submit button using ajax jquery?Can someone help my finding out whats wrong?
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
Here is the code
<body>
<input name="files[]" type="file" multiple />
<input type="hidden" name="hiddenval" id="hiddenval" value="">
<button id="upload" value="Upload" class="btn btn-success" />
</body>
</html>
<script>
$(document).on("click", "#upload", function() {
var outputdata = [];
$.ajax({
url: "upload1.php",
type: "POST",
data: new Form(this),
contentType: false,
processData: false,
success: function(files, data, xhr) {
outputdata.push(files);
$('#hiddenval').val(outputdata)
}
});
});
</script>
add id to this input for easier get value.
<input name="files[]" type="file" multiple id="files"/>
Includes values from this input to data:
$(document).on("click", "#upload", function() {
var outputdata = [];
var fileSelect = document.getElementById('files');
var files = fileSelect.files;
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('photos[]', file, file.name);
}
$.ajax({
url: "upload1.php",
type: "POST",
data: formData,
contentType: false,
processData:false,
success: function(files,data,xhr)
{
outputdata.push(files);
$('#hiddenval').val(outputdata);
}
});
});
Refer: http://blog.teamtreehouse.com/uploading-files-ajax

Ajax - send button value to php

I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
</script>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
PHP:
<?php
$name = $_POST['data'];
echo $name;
?>
It doesn't working...
try this out, i just did and worked fine
here's my js file
<html>
<head>
</head>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
<footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function() {
var val = $(this).val();
$.ajax({
// your uri, pay attention if the post is going to the right place
url: "try.php",
type: "POST",
// myVar = name of the var that you will be able to call in php
// val = your data
data: {'myVar': val}
});
});
});
</script>
</footer>
</html>
and here's my php
<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses
Make proper json string to send data. You are having extra ; there.
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
And get it with data key in php.
<?php
$name = $_POST['data'];
echo $name;
?>
Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.
<button id="example" name="name_example" value="some_value">
1</button>
$(document).ready(function () {
$('#example').click(function() {
var buttonValue = $(this).val();
$.ajax({
url: "try.php", //assuming that your html file is in the same folder as
//your php script.
type: "POST",
data: {'example': buttonValue}
});
});
});
look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/
In your .php file, which should be in the same folder as your html file doing the request you will have:
<?php
echo '<pre>'; print_r($_POST); die; // see if you now have those vars.
?>

Upload photo in background with ajax

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);
}

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