After reading the accepted answer on this post, I am trying to implement the same but not able to figure out the problem. When I select a file, nothing is available in $_FILES on the server side. What am I doing wrong? I am using Apache 2.2.22, Yii 1.12
My view file
<form enctype="multipart/form-data" action='/webapp/index.php/emu/default/uploadFile' method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input id="files" type="file" >
</form>
<script>
document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if ( xhr.upload ) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
var url='/webapp/index.php/emu/default/uploadFile';
xhr.open('post', url, true);
xhr.send(file);
}, false);
</script>
Controller action:
public function actionUploadFile(){
Yii::log(CJSON::encode($_FILES['files']));
}
Yii::log outputs following:
2014/12/16 19:59:29 [error] [php] Undefined index: files
To upload a file transparently via ajax you'll have to use a FormData object
var file = this.files[0];
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append('files', file);
...
xhr.send(data);
Related
How can I send my converted exif coordinates (in decimals) to my db using php and mysql? I'm using one file for this (addnew.php)
I'm sending information through a form in php like:
if(isset($_POST['btn_submit'])){
$username = $_POST['userName'];
$watervisibility = $_POST ['waterVisibility'];
$divinglocation = $_POST['divingLocation'];
$imgFile = $_FILES['user_art']['name'];
$tmp_dir = $_FILES['user_art']['tmp_name'];
$imgSize = $_FILES['user_art']['size'];
I also use libraries to convert exif to decimals ( on change ) to avoid clicking submit. This is all still in the same php file (addnew.php) (this is where i'm having a problem)
var lat;
var latref;
var long;
var longref;
var dec;
var myLatLng;
document.getElementById("input-group").onchange = function(e) {
EXIF.getData(e.target.files[0], function() {
//console.log(EXIF.pretty(this));
long = EXIF.getTag(this, 'GPSLongitude');
longref = EXIF.getTag(this, 'GPSLongitudeRef');
lat = EXIF.getTag(this, 'GPSLatitude');
latref = EXIF.getTag(this, 'GPSLatitudeRef');
dec = dms2dec(long, longref, lat, latref);
console.log("Decimal 1: " + dec[0] + " Decimal 2: " + dec[1]);
console.log("Longref: " + longref);
console.log("Latref: " + latref);
console.log("Long Length: " + long.length);
console.log("Longtitude: " + long);
console.log("Latitude: " + lat);
myLatLng = {lat: dec[1], lng: dec[0]}
myLat = {lat: dec[1]}
myLng = {lng: dec[0]}
console.log(myLat);
console.log(myLng);
});
}
Now I got the decimals and basically just want to send
myLat = {lat: dec[1]}
myLng = {lng: dec[0]}
to my db through php at the same time i'm submitting everything else.
I've tried Send JSON data from Javascript to PHP but I can't seem to get the hang of it
Any ideas?
Thanks!
To send javascript obj to php using json and ajax:
js:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
to use that object in php:
$obj = json_decode($_POST["myData"]);
echo $obj->var;
I'm trying to capture audiorecorder (https://github.com/cwilso/AudioRecorder) and send the blob through Ajax a php file, which will receive the blob content and create the file(the wave file in this case).
Ajax call:
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
$.ajaxFileUpload({
url : "lib/vocal_render.php",
secureuri :false,
dataType : blob.type,
data: blob,
success: function(data, status) {
if(data.status != 'error')
alert("boa!");
}
});
});
and my php file (vocal_render.php):
<?php
if(!empty($_POST)){
$data = implode($_POST); //transforms the char array with the blob url to a string
$fname = "11" . ".wav";
$file = fopen("../ext/wav/testes/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}?>
P.S:I'm newbie with blobs and ajax.
Thanks in advance.
Try uploading the file as form data
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
var data = new FormData();
data.append('file', blob);
$.ajax({
url : "lib/vocal_render.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert("boa!");
},
error: function() {
alert("not so boa!");
}
});
});
.
<?php
if(isset($_FILES['file']) and !$_FILES['file']['error']){
$fname = "11" . ".wav";
move_uploaded_file($_FILES['file']['tmp_name'], "../ext/wav/testes/" . $fname);
}
?>
According to the documentation, by using XMLHttpRequest.send() you can use the Blob object directly.
var blob = new Blob(chunks, { 'type' : 'audio/webm' });
var xhr = new XMLHttpRequest();
xhr.open('POST', '/speech', true);
xhr.onload = function(e) {
console.log('Sent');
};
xhr.send(blob);
I've tried this and it works like a charm.
I have been trying a dozen ways to save a dataurl generated from an svg to my server. This code seems like it should be working based on other threads I've read here but for some reason it just creates a .png file with 0kb. I went ahead and just copy/pasted the dataurl right into my script to avoid any data being sent to php issues right now, I just want to see the php create the image correctly. Here's my code:
$img="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAiYAAAGQCAYAAACatauzAAAgAElEQVR4Xuy9C5Bd1XkuuPY5p1+ipW61QOiBUSMhB0dcJGI8uTUxVy1V2amZugO4Mjck4IzEVPCYZKYQju+ti2OwYrA9Vbk2eG4lUGqqJBkJhkx5eNzM1MSuWC2TVDnXsvUA2TJCUguQEBJqdevZj3POnv/f56zuv0+fx36svfdaa/+rSjRSr73W2t+/9t7f+p+O4MYIMAKMACPACDACjIAmCDiarIOXwQgwAowAI8AIMAKMgGBiwpuAEWAEGAFGgBFgBLRBgImJNqLghTACjAAjwAgwAowAE5OE98DA9u29or34KAB/YM+DD7+e8PQ8HSPACDACjAAjoDUCTEwSFM/A7m3rcsIZcoXoqU476gjnNVe4rzFJSVAQPBUjwAgwAoyAtggwMUlQNBt2De4Ar55Ndy+8QVwrlcRbV8bciVLJkwH8Z0wId0/Zzb0m8lN7h/74keEE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Lkg8DRlQffv2J1NrbTekENlrvfPhNsqMAMpFZHArRWBTQKA2rUIAPItBIveGHsU+CZL7vfvgBLD4VyYnTEZCjllkHsVtD2YuAiskbY+hNcQ4qD2AtDzmmgAgl0ERwQ/AEO+7KAenCjYGiEAKxhQqtdHUMjFAa/K0EjGaDRhktfP/7/BV33AYqzBGklvMcnwE6rBY3MYBtNocXFjaDGFOh6Cvj0D45FvaMNk8Gf7kZdOBoCoyEwGgKjITAaAqMhMIhCAAC+P4HZvnVG3QAAAABJRU5ErkJggg==";
$filedata = substr($img, strpos($img,",")+1);
file_put_contents("testfile2.png", base64_decode($filedata));
echo "file created";
Here's the jquery code that's generating the data. I just copy it from the alert to test in this script:
$("#testclick").click(function() {
var svg = document.getElementById("map").innerHTML; // or whatever you call it
//alert(svg);
$('#load-target').html(svg);
var canvas = $('#load-target svg')[0];
try {
svgAsDataUri(canvas, null, function(uri) {
var image = new Image();
image.src = uri;
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
var a = document.createElement('a');
a.download = name;
alert(canvas.toDataURL('image/png'));
a.href = canvas.toDataURL('image/png');
document.body.appendChild(a);
a.click();
}
//alert(uri);
$.post("http://www.srqnews.com/maps/create.php",
{
type:"PNG",
datauri:uri
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
} catch(err) {
alert(err.message);
}
});
Hi I need to get the form data to be submitted along with the canvas image. Then use that form data to name the file saving on the server. I am just getting to grips with PHP, so any help would be amazing.
This is my working example which will save the same named file to the server.
HTML
<form action="name.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="button" onclick="saveImage();formSubmit();" value="Submit form">
</form>
JS
function saveImage(){
var xmlhttp;
xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//do something with the response
}
}
xmlhttp.open("POST","upload.php",true);
var oldCanvas = document.getElementById('colors_sketch').toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
xmlhttp.setRequestHeader("Content-type", "application/upload")
xmlhttp.send(oldCanvas);
}
PHP
$data = file_get_contents('php://input');
$canvasImg = imagecreatefrompng($data);
$width = imagesx($canvasImg);
$height = imagesy($canvasImg);
$outImg = imagecreatetruecolor($width, $height);
$color = imagecolorallocatealpha($outImg, 255, 255, 255, 127);
imagefill($outImg, 0, 0, $color);
imagecopy($outImg, $canvasImg, 0, 0, 0, 0, $width, $height);
imagepng($outImg, 'test.png');
Here are steps to send your form and image to upload.php
First create a data package to send that includes your serialized image and form. Here I use jquery to serialize your form (or serialize it yourself without jquery).
// serialize and concatenate both form and canvas image
var package=$("form").serialize() + "&imageDataURL="+canvas.toDataURL();
Then POST it with AJAX to your PHP server:
// ajax it
postImagePlusForm();
function postImagePlusForm(){
$.ajax({
type: "POST",
url: "upload.php",
data: package,
success: function(value) {
// ...we have success!
}
});
}
And finally catch it and process it in php:
<?php
if ( isset($_POST["imageDataURL"]) && !empty($_POST["imageDataURL"]) ) {
// create $dataURL
$dataURL = $_POST["imageDataURL"];
// Extract base64 data
// we have an unneeded header, zap it
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode
$data = base64_decode($data);
// Save
$fp = fopen('newImage.png', 'w');
fwrite($fp, $data);
fclose($fp);
}
if ( isset($_POST["formData"]) && !empty($_POST["formData"]) ) {
$formData = $_POST['formData'];
foreach ($formValue as $x) {
// do whatever you need to do with each form value ($x)
}
}
This question was asked numerous times on SO.
I already answered the same question here:
https://stackoverflow.com/a/13198699/1090562
In short, this can be achieved with this, for more details - read the link
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: canvas.toDataURL();
}
}).done(function(o) {
console.log('saved');
});
Hi I'm wanting to post a variable from ajax js file to a php file. here is my attempt so far.
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
here is my php file
<?php
print_r($_POST);
$node = $_POST['deletenode'];
print "node to be deleted: $node";
?>
nothing comes up in my php file, what can be the issue. my ajax request is intact and working right too. thank you and here is my handle request.
function handleRequest(request) {
// we only care for now about when we get to readyState 4
// which means the request completed and we have the response back
if(request.readyState == 4){
//alert("response: " + request.responseText); // check to see what
// we got back just for testing
// now get response's TEXT and put into document (specify where)
// below we have an html element with the id as timeLoc
json= eval ("(" + request.responseText + ")");;
//alert ("json="+json); //tests what was recieved
//clicking the close button
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}// end readystate=4
}//end handle request
Remember you have to send the data as key/value pairs - request.send("deletenode=" + encodeURIComponent(deletenode));
I'm not sure if this is a copy/paste error, but if that's your actual code you appear to be missing a few curly braces closes. And have a double;; at the end of your eval line. This is the code tidied up with the extra curly braces, does that work?
function handleRequest(request) {
if(request.readyState == 4){
json= eval ("(" + request.responseText + ")");
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}
}
}