How do you upload file(s) with AJAX - php

I am currently trying to upload a file through a form I made, using jQuery. This is what I am attempting to do:
function ajax_upload(){
var formData = new FormData($('form#userform'));
$.ajax({
url: location.protocol + "//" + location.host + "/profile/uploadPicture",
dataType: 'json',
data: formData,
type: 'post',
success: function(data, status){
if (data.status == 'error') {
$('#error').html(data.msg);
}
else {
var filename = location.protocol + "//" + location.host + "/data/profiles/" + data.msg;
$('input#filename').val(filename);
close_upload_form();
pop_profilechanger(filename);
}
}
});
return false;
}
the form appears to post to the backend, but while trying to return the filename from the uploaded file in a JSON object like:
echo json_encode(array('status' => $status, 'msg' => $msg));
Is there something wrong?
Please tell me

This is how I do it. If you want more information, rather than just my pasted code, check out this http://www.html5rocks.com/en/tutorials/file/dndfiles/ because my code was made for drag and drop files
handleFiles : function(files, evt, target)
{
console.log(target);
$.each(files, function(index, value)
{
var file = value;
reader = new FileReader();
reader.onload = function(evt)
{
var li = $("<li class='uploading'><img data-image-id='0' src='" + evt.target.result + "' /></li>");
target.find('.imagesList').append(li);
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append('image', file);
request.open("Post", settings.uploadImageUrl);
request.addEventListener("load", function(evt)
{
var id = evt.target.responseText;
li.removeClass('uploading');
li.find('img').attr('data-image-id', id);
}, false);
request.send(formData);
};
reader.readAsDataURL(value);
});
},

Related

ajax upload image with another data in form

my problem is: I want to upload image/pdf with ajax. In my code i have multiple inputs but i do not use FormData() to pass data from input to my upload.php. All work perfect. So here for better imagine:
$('#addData').on('click', function(){
var c_zakazky = $('#c_zakazky').val();
var pozicia = $('#pozicia').val();
var p_cislo = $('#p_cislo').val();
var stav = $('#stav').val();
var tech = $('#tech').val();
var zar = $('#zar').val();
var operator = $('#op').val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;
//alert(dokument);
$.ajax({
url: 'add.php',
type: 'POST',
processData: false,
contentType: false,
data: {
otk: 1,
c_zakazky: c_zakazky,
pozicia: pozicia,
p_cislo: p_cislo,
stav: stav,
tech: tech,
zar: zar,
operator: operator,
datum: datum
},
success: function(data){
$('#live_data').html(data);
$('#modalInsert').modal('hide');
$('#c_zakazky').val();
$('#pozicia').val();
$('#p_cislo').val();
$('#stav').val();
$('#tech').val();
$('#zar').val();
$('#op').val();
$('#dokument').val();
fetch_data_otk();
alert(data);
}
});
});
And now if i want to iclude image to this how to do it? I tried add this:
var data = new FormData();
data.append('image', $('#image').prop('files')[0]);
console.log(data);
but when i select image/pdf and hit upload in console (data) is empty and i do not know hot to do it.
Please Try this, if you want console formdata object attributes.
// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
// Display the key/value pairs
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
Please take a look at the sample code to save your data and image/media files to form_data and then using AJAX to save the said data in the backend
<!DOCTYPE html>
<head>
<title>Example</title>
</head>
<body>
<form enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_img" name="img_url" multiple>
</div>
<input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
</form>
</body>
<script>
function myfunction(){
var form_data = new FormData();
var image = document.getElementById('upload_img').files.length;
for (var x = 0; x < image; x++) {
form_data.append("image", document.getElementById('upload_img1').files[x]);
}
$.ajax({
url : 'your-backend-file-with-DB-Query.php',
method : 'POST',// OR GET
data: form_data,
dataType: 'json',
success:function(data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
</script>
</html>
I unable to understand, what exactly you want but please try below code, it will submit all form elements data:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&post1&post2",
success : function(){
},
error : function(){
}
}
OR
$.ajax({
url: 'url',
type: "POST",
data: new FormData(this),
success : function(){
},
error : function(){
}
});
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
add dynamic data also
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
So thank you for help. Now it works perfect. SOLUTION:
I changed only script (php code is still same)
//pridanie udajov
$('#addData').on('click', function(){
var fileInput = document.querySelector('form input[type=file]');
var attachment = fileInput.files[0];
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;
var formData = new FormData();
formData.append('otk', 1);
formData.append('c_zakazky', $('#c_zakazky').val());
formData.append('pozicia', $('#pozicia').val());
formData.append('p_cislo', $('#p_cislo').val());
formData.append('stav', $('#stav').val());
formData.append('tech', $('#tech').val());
formData.append('zar', $('#zar').val());
formData.append('op', $('#op').val());
formData.append('datum', datum);
formData.append('image', $('#image').prop('files')[0]);
console.log(formData);
$.ajax({
url: 'add.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data){
$('#live_data').html(data);
$('#modalInsert').modal('hide');
$('#c_zakazky').val();
$('#pozicia').val();
$('#p_cislo').val();
$('#stav').val();
$('#tech').val();
$('#zar').val();
$('#op').val();
$('#dokument').val();
fetch_data_otk();
alert(data);
}
});
});

How to create file from 'blob:http://' url

I have blob:http://unifiedmain.localhost.com/a4580f39-8f9d-4e8c-8e4b-02a6bd2df3df url and i want to create actual file file from this.
I've used
PHP code :
file_put_contents('E:\www\nginx\html\unifinedmainsite\123.mp3', file_get_contents($_REQUEST['id']));.
javascript code:
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
jQuery.ajax({
type: "POST",
url: BASEURL+"/index.php?saveFileInSession=true",
data: "id="+reader.result,
success: function(response) {
console.log(response);
}
});
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', 'blob:http://unifiedmain.localhost.com/a4580f39-8f9d-4e8c-8e4b-02a6bd2df3df');
xhr.send();
file is generating with actual size but i can not open it ,what is i am doing wrong?
Do i have to pass some header or something?so that i can play my saved/uploaded .mp3 file?
please help.

AJAX generated order list li id not post via data

I am getting the list of root folders of OneDrive and sub folders using AJAX post using the following code.
$(document).ready(function(){
$(".driveFolders li").click(function(){
var folderId = $(this).attr( "id" );
var objlst= $(this);
var request;
request = $.ajax({
url: url,
method: "POST",
data: {'id': folderId},
ContentType: 'application/json'
});
request.done(function( response ) {
var result = jQuery.parseJSON(response);
var html="";
for(var i = 0, l = result.length; i < l; i++){
var subFolderID = result[i].id;
html += "<li id="+subFolderID+"'>" + result[i].name + "</li>";
}
$("#childern").html(html);
});
})
})
It returns the list of all files and folders. Now, I got the AJAX to generate data of li elements and I am sending a AJAX request again using the following code:
$(document).on("click", "#childern li", function () {
var subFolderID = $(this).attr("id");
var objlst = $(this);
var request;
request = $.ajax({
context: this,
url: url,
method: "POST",
data: { 'id': subFolderID },
ContentType: 'application/json'
});
request.done(function (response) {
var result = jQuery.parseJSON(response);
var html = "";
for (var j = 0, l = result.length; j < l; j++) {
}
$("#childern").html(html);
});
});
It returns an error
folders does not exist.
While sending the folder id manually, I receive all files. Here is my controller code:
public function GetFolderContent(){
$this->load->library('STOneDrive');
if (!$this->stonedrive->is_Connected) {
$refreshToken = "";
$this->stonedrive->Reconnect($refreshToken);
}
$contents = $this->stonedrive->LoadRootFolders(urldecode($this->input->post('id')));
$result = array();
foreach($contents as $content){
array_push($result,array('id' => $content->getId(),'name'=>$content->getName(),'size'=> ''));
}
echo json_encode($result);
}
There is mistake to append id to li tag:
change
html += "<li id="+subFolderID+"'>" + result[i].name + "</li>";
to following
html += "<li id='"+subFolderID+"'>" + result[i].name + "</li>";
In ajax code method replace with type and content-type with dataType.

Multiple wfs from database; changes the url

I need to show multiple wfs features into map. The requested url is http://localhost/pdan/map.php?id=150 This is what I have done:
var id = <?php echo $_REQUEST['id']; ?>;
function getVector(obj) {
var url = "";
var geojsonFormat = new ol.format.GeoJSON();
var vectorSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = 'http:192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
$.ajax({url: url, dataType: 'jsonp', jsonp: false, cache:false});
},
strategy: ol.loadingstrategy.bbox
});
window.loadFeatures = function(response) {
vectorSource.addFeatures(geojsonFormat.readFeatures(response));
};
return new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
}
function getObject(id) {
var result;
$.ajax({
url: "dbQueries.php",
async: false,
cache: false,
dataType: "JSON",
data: {'query': 110, 'id': id},
success: function (data) {
result = data;
}
});
return result;
}
var vector = [];
var rowObject = getObject(id);
var size = Object.size(rowObject);
//Prepare vector Layer
if (size != 0) {
for (var i = 0; i < size; i++) {
vector[i] = getVector(rowObject[i]);
}
}
//Now Initialise map
var map = createMap();
var graticule = getGraticule();
graticule.setMap(map);
//Add vector to the map
if (size != 0) {
for (var i=0; i<size; i++) {
map.addLayer(vector[i]);
}
}
Everything seems okey to me but the url is changed and in the console I get error as:
GET
http://localhost/pdan/192.168.0.101:8082/geoserver/pdan/ows [HTTP/1.1 403 Forbidden 3ms]
What am I missing here?
The problem was with the url I requested. It should be
var url = 'http://192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
instead of
var url = 'http:192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';

submit form data and files using phonegap?

I have created simple html form that contains text inputs, text area , files such as uploading images ..
how could I submit this form data when turning it into phone gap application that contains user registration to his data and photo and cv document?
when submitting data it should be sent to php page where mysql insert will held?
I have tried the serialize method face problems in getting data in th php page
also couldn't find the way to upload file and images??
any help???
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("Hello ");
$("#button").click(function(evt){
var name = $("#name").val();
var message = $("#message").val();
var sendData = { "name": name, "message": message };
$.ajax({
type: "POST",
url: "http://localhost/webs/main/ajax/process.php",
data: sendData,
success: function(data) {
log.console(data);
$("#info").html(data);
}
});
alert("Hello ");
alert($("#test").val());
alert($("#name").val());
alert($("#message").val());
return false;
});
}
Upload image using phonegap
============================
function uploadImage(){
//Using Camera
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: Camera.DestinationType.FILE_URI });
//Using library
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
}
function onFailcapturePhoto(message) {
console.log("Message = " + message);
}
function uploadPhoto(imageURI) {
var imagefile = imageURI;
$('#vImage').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}
On your php file
=================
file_put_contents("file.txt", print_r($_FILES, true));
Post Form data and Image together
================================
// Here first submit your form input data after successfully submit upload image call
$('#submit').on('click', function(event){
if(event.handled !== true)
{
var ajax_call = serviceURL;
var str = $('#form').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
$.each(response, function(key, value) {
// after success submit data
if(response){
var imagefile = $('#vImage').attr('src');
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.mimeType="image/png";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
});
}
});
event.handled = true;
}
return false;
})

Categories