my question is an annoying combination of multiple smaller questions on stackoverflow as far as i've been able to find, but i can't get it figured out.
I'm trying to send an audio file over ajax, that works fine, but i also want to include the location where it was uploaded/ recorded. This is what I have made up reading through multiple similar question:
(it does not work)
function getLocation() {
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
function foundLocation(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
//alert("LAT : "+latitude +", LONG : "+longitude);
return [longitude, latitude];
}
}
function noLocation() {
//alert('Could not find location');
}
function uploadAudio(mp3Data){
var pos = getLocation();
var longitude = pos[0];
var latitude = pos[1];
var reader = new FileReader();
reader.onload = function(event){
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
console.log("mp3name = " + mp3Name);
fd.append('fname', mp3Name);
fd.append('data', event.target.result);
fd.append('longitude', longitude);
fd.append('latitude', latitude);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
//console.log(data);
log.innerHTML += "
" + data;
});
};
reader.readAsDataURL(mp3Data);
}
The php script I have to handle the data is as follows:
<?php
if(!is_dir("recordings")){
$res = mkdir("recordings",0777);
}
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
//echo ($decodedData);
$filename = 'audio_recording_' . date( 'Y-m-d-H-i-s' ) .'.mp3';
// write the data out to the file
$fp = fopen('recordings/'.$filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
I want to be able to retrieve the location with something like $latitude = $_POST['longditude'];
Right now I have no idea how to make JS return multiple data in the getLocation() function, nor how to make ajax send all this data properly. Any help will be greatly appreciated!