Upload multiple image using AJAX, PHP and jQuery - javascript

I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!

Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

Related

Why is my Ajax cannot save data into database? Laravel with Ajax

I am trying to save data using ajax. The ajax is inside my javascript file and passed to my controller and route. However the issue is it cannot save the data into my database.
Here is my jquery.hotspot.js file that include ajax:
(function ($) {
var defaults = {
// Object to hold the hotspot data points
data: [],
// Element tag upon which hotspot is (to be) build
tag: 'img',
// Specify mode in which the plugin is to be used
// `admin`: Allows to create hotspot from UI
// `display`: Display hotspots from `data` object
mode: 'display',
// HTML5 LocalStorage variable where hotspot data points are (will be) stored
LS_Variable: '__HotspotPlugin_LocalStorage',
// CSS class for hotspot data points
hotspotClass: 'HotspotPlugin_Hotspot',
// CSS class which is added when hotspot is to hidden
hiddenClass: 'HotspotPlugin_Hotspot_Hidden',
// Event on which the hotspot data point will show up
// allowed values: `click`, `hover`, `none`
interactivity: 'hover',
// Action button CSS classes used in `admin` mode
save_Button_Class: 'HotspotPlugin_Save',
remove_Button_Class: 'HotspotPlugin_Remove',
send_Button_Class: 'HotspotPlugin_Send',
// CSS class for hotspot data points that are yet to be saved
unsavedHotspotClass: 'HotspotPlugin_Hotspot_Unsaved',
// CSS class for overlay used in `admin` mode
hotspotOverlayClass: 'HotspotPlugin_Overlay',
// Enable `ajax` to read data directly from server
ajax: false,
ajaxOptions: { url: '' },
listenOnResize: true,
// Hotspot schema
schema: [
{
'property': 'Title',
'default': ''
},
{
'property': 'Message',
'default': ''
}
]
};
// Constructor
function Hotspot(element, options) {
var widget = this;
// Overwriting defaults with options
this.config = $.extend(true, {}, defaults, options);
this.element = element;
// `tagElement`: element for which hotspots are being done
this.tagElement = element.find(this.config.tag);
// Register event listeners
$.each(this.config, function (index, fn) {
if (typeof fn === 'function') {
widget.element.on(index + '.hotspot', function (event, err, data) {
fn(err, data);
});
}
});
if (this.config.mode != 'admin' && this.config.listenOnResize) {
$(window).on('resize', function () {
$(element).find('.' + widget.config.hotspotClass).remove();
widget.init();
});
}
if (this.config.tag !== 'img') {
widget.init();
return;
}
if (this.tagElement.prop('complete')) {
widget.init();
} else {
this.tagElement.one('load', function (event) {
widget.init();
});
}
}
Hotspot.prototype.init = function () {
this.parseData();
// Fetch data for `display` mode with `ajax` enabled
if (this.config.mode != 'admin' && this.config.ajax) {
this.fetchData();
}
// Nothing else to do here for `display` mode
if (this.config.mode != 'admin') {
return;
}
this.setupWorkspace();
};
Hotspot.prototype.createId = function () {
var id = "";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 7; i++) {
id += letters.charAt(Math.floor(Math.random() * letters.length));
}
return id;
};
Hotspot.prototype.setupWorkspace = function () {
var widget = this;
// `data` array: to contain hotspot objects
var data = [];
var tHeight = $(widget.tagElement[0]).height(),
tWidth = $(widget.tagElement[0]).width(),
tOffset = widget.tagElement.offset(),
pHeight = $(widget.element[0]).height(),
pWidth = $(widget.element[0]).width(),
pOffset = widget.element.offset();
// Create overlay for the tagElement
$('<span/>', {
html: '<p>Click this Panel to Store Messages</p>'
}).css({
'height': (tHeight / pHeight) * 100 + '%',
'width': (tWidth / pWidth) * 100 + '%',
'left': (tOffset.left - pOffset.left) + 'px',
'top': (tOffset.top - pOffset.top) + 'px'
}).addClass(widget.config.hotspotOverlayClass).appendTo(widget.element);
// Handle click on overlay mask
this.element.delegate('span', 'click', function (event) {
event.preventDefault();
event.stopPropagation();
// Get coordinates
var offset = $(this).offset(),
relativeX = (event.pageX - offset.left),
relativeY = (event.pageY - offset.top);
var height = $(widget.tagElement[0]).height(),
width = $(widget.tagElement[0]).width();
var hotspot = { x: relativeX / width * 100, y: relativeY / height * 100 };
var schema = widget.config.schema;
for (var i = 0; i < schema.length; i++) {
var val = schema[i];
var fill = prompt('Please enter ' + val.property, val.default);
if (fill === null) {
return;
}
hotspot[val.property] = fill;
}
data.push(hotspot);
// Temporarily display the spot
widget.displaySpot(hotspot, true);
});
// Register admin controls
var button_id = this.createId();
$('<button/>', {
text: "Save data"
}).prop('id', ('save' + button_id)).addClass(this.config.save_Button_Class).appendTo(this.element);
$('<button/>', {
text: "Remove data"
}).prop('id', ('remove' + button_id)).addClass(this.config.remove_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('save' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.saveData(data);
data = [];
});
$(this.element).delegate('button#' + ('remove' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.removeData();
});
if (this.config.ajax) {
$('<button/>', {
text: "Send to server"
}).prop('id', ('send' + button_id)).addClass(this.config.send_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('send' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.sendData();
});
}
};
Hotspot.prototype.fetchData = function () {
var widget = this;
// Fetch data from a server
var options = {
data: {
HotspotPlugin_mode: "Retrieve"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function (data) {
// Storing in localStorage
localStorage.setItem(widget.config.LS_Variable, data);
widget.parseData();
})
.fail($.noop);
};
Hotspot.prototype.parseData = function () {
var widget = this;
var data = this.config.data,
data_from_storage = localStorage.getItem(this.config.LS_Variable);
if (data_from_storage && (this.config.mode === 'admin' || !this.config.data.length)) {
data = JSON.parse(data_from_storage);
}
$.each(data, function (index, hotspot) {
widget.displaySpot(hotspot);
});
};
Hotspot.prototype.displaySpot = function (hotspot, unsaved) {
var widget = this;
var spot_html = $('<div/>');
$.each(hotspot, function (index, val) {
if (typeof val === "string") {
$('<div/>', {
html: val
}).addClass('Hotspot_' + index).appendTo(spot_html);
}
});
var height = $(this.tagElement[0]).height(),
width = $(this.tagElement[0]).width(),
offset = this.tagElement.offset(),
parent_offset = this.element.offset();
var spot = $('<div/>', {
html: spot_html
}).css({
'top': (hotspot.y * height / 100) + (offset.top - parent_offset.top) + 'px',
'left': (hotspot.x * width / 100) + (offset.left - parent_offset.left) + 'px'
}).addClass(this.config.hotspotClass).appendTo(this.element);
if (unsaved) {
spot.addClass(this.config.unsavedHotspotClass);
}
if (this.config.interactivity === 'hover') {
return;
}
// Overwrite CSS rule for `none` & `click` interactivity
spot_html.css('display', 'block');
// Initially keep hidden
if (this.config.interactivity !== 'none') {
spot_html.addClass(this.config.hiddenClass);
}
if (this.config.interactivity === 'click') {
spot.on('click', function (event) {
spot_html.toggleClass(widget.config.hiddenClass);
});
} else {
spot_html.removeClass(this.config.hiddenClass);
}
};
Hotspot.prototype.saveData = function (data) {
if (!data.length) {
return;
}
// Get previous data
var raw_data = localStorage.getItem(this.config.LS_Variable);
var hotspots = [];
if (raw_data) {
hotspots = JSON.parse(raw_data);
}
// Append to previous data
$.each(data, function (index, node) {
hotspots.push(node);
});
this.data=data;
$.ajax({
type:"POST",
url:"/store",
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
Title:$('#Title').val(),
Message: $('#Message').val(),
x:$('#relativeX').val(),
y: $('#relativeY').val(),
},
success: function(data){
console.log(data,d);
},
error: function(data)
{
console.log(data);
},
});
localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));
this.element.trigger('afterSave.hotspot', [null, hotspots]);
};
Hotspot.prototype.removeData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null) {
return;
}
if (!confirm("Are you sure you wanna do everything?")) {
return;
}
localStorage.removeItem(this.config.LS_Variable);
this.element.trigger('afterRemove.hotspot', [null, 'Removed']);
};
Hotspot.prototype.sendData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null || !this.config.ajax) {
return;
}
var widget = this;
var options = {
data: {
HotspotPlugin_data: localStorage.getItem(this.config.LS_Variable),
HotspotPlugin_mode: "Store"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function () {
widget.element.trigger('afterSend.hotspot', [null, 'Sent']);
})
.fail(function (err) {
widget.element.trigger('afterSend.hotspot', [err]);
});
};
$.fn.hotspot = function (options) {
new Hotspot(this, options);
return this;
};
}(jQuery));
Here is my route:
Route::get('hotspots','ImageController#getPin');
Route::post('store','ImageController#storePin')->name('store.storePin');
Here is my ImageController.php:
public function getPin()
{
$pin= Pin::select('Title','Message','x','y');
return hotspot::of($pin)->make(true);
}
public function storePin(Request $request)
{
$validation = Validator::make($request->all(), [
'Title' => 'required',
'Message' => 'required',
'x'=>'required',
'y'=>'required',
]);
if ($request->get('save','button_id') == "insert")
{
$pin = new Pin();
$pin->Title=$request->Title;
$pin->Message= $request->Message;
$pin->x = $request->relativeX;
$pin->y =$request->relativeY;
$pin->save();
//return Request::json($request);
}
}
Here is my hotspot.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Picomment Hotspot</title>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/bootsrap.min.css') }}">
<script type="text/javascript" src="{{ asset ('js/jquery.min.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/jquery.hotspot.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset ('css/style.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
<div class="col-md-6" style="margin-top: 40px;">
<div id="theElement-a">
<img src="{{ asset('storage/'.$files) }}" alt="" title="">
</div>
</div>
</div>
<script type="text/javascript" src="{{ asset ('js/jquery.hotspot.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#theElement-a").hotspot({
mode: "admin",
// uncomment
/*ajax: true,
ajaxOptions: {
'url': 'links.to.server'
},*/
interactivity: "click",
LS_Variable: "HotspotPlugin-a",
afterSave: function(err, data) {
if (err) {
console.log('Error occurred', err);
return;
}
alert('Saved');
// `data` in json format can be stored
// & passed in `display` mode for the image
localStorage.clear();
console.log(data);
},
afterRemove: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
window.location.reload();
},
afterSend: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
}
});
});
</script>
</body>
</html>

Get the name of the uploaded file

I am new to AngularJS1 and Js. Here i am uploading a file which will be saved on my drive as well as in mongodb. What I am trying to do is to get the uploaded file name which can easily be seen here in attached picture. Kindly help me out with this.
$scope.uploadedFileList.push(p);
$('#addproFile').ajaxfileupload({
action: 'http://' + window.location.hostname + ':' + window.location.port + '/api/upload',
valid_extensions : ['md','csv','css', 'txt'],
params: {
dummy_name: p
},
onComplete: function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
/* $scope.nameString = uploadedFileList.join(',');
$scope.$apply();*/
},
onCancel: function() {
console.log('no file selected');
}
});
This is my controller
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true == settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )
this is my ajax file upload function

Javascript module parttern ajax

I am learning javascript design patterns. So am converting my rough jquery code into cleaner module pattern. The question is, how will i call a click event after ajax has loaded in module pattern (Object literal). I used to solve it using $(document).ajaxcomplete(callback).
here is the working supergetti code
$('.meidaBtn, #media_load_btn').on('click', function(event) {
event.preventDefault();
$('.media').show(500);
$('#mediaBox').html('Loading...');
var link = location.origin + '/dashboard/media';
$.ajax({
url: link
}).done(function(data) { // data what is sent back by the php page
$('#mediaBox').html(data); // display data
// Click through
$('.imageBox img').bind('click', function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
$('.media').hide();
});
});
});
Here is the javascript module pattern / object literal
var mediaPlugin = {
init: function() {
this.cacheDom();
this.bindEvents();
},
// Cache Dom
cacheDom: function() {
this.baseUrl = location.origin + '/dashboard/media';
this.$button = $('.meidaBtn, #media_load_btn');
this.$media = $('.media');
this.$mediaBox = $('#mediaBox');
this.$imageBox = $('.imageBox img');
},
// Bind Events
bindEvents: function() {
this.$button.on('click', this.render.bind(this));
this.$imageBox.on('click', this.addImage.bind(this));
},
// Show Data
render: function(e) {
e.preventDefault();
this.$media.show(500);
this.loadData();
},
// Load the data
loadData: function() {
var that = this;
$.ajax({
url: this.baseUrl,
type: 'GET',
success: function(data) {
// console.log(that.$mediaBox);
that.$mediaBox.html(data);
},
error: function() {
console.log("An error occored!");
},
complete: function() {
// console.log("I am now complete");
// that.loadMore();
}
});
},
// Add Image
addImage: function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
this.$media.hide();
}
};
mediaPlugin.init();
The method provided below adds a simple property to the object which is used as a delegate/callback. You simply point your function to it and then it is called automatically since it is called in the complete event.
var mediaPlugin = {
init: function() {
this.cacheDom();
this.bindEvents();
},
// Cache Dom
cacheDom: function() {
this.baseUrl = location.origin + '/dashboard/media';
this.$button = $('.meidaBtn, #media_load_btn');
this.$media = $('.media');
this.$mediaBox = $('#mediaBox');
this.$imageBox = $('.imageBox img');
},
// Bind Events
bindEvents: function() {
this.$button.on('click', this.render.bind(this));
this.$imageBox.on('click', this.addImage.bind(this));
},
// Show Data
render: function(e) {
e.preventDefault();
this.$media.show(500);
this.loadData();
},
loadDataComplete: function() {},
// Load the data
loadData: function() {
var that = this;
$.ajax({
url: this.baseUrl,
type: 'GET',
success: function(data) {
// console.log(that.$mediaBox);
that.$mediaBox.html(data);
},
error: function() {
console.log("An error occored!");
},
complete: function() {
// console.log("I am now complete");
// that.loadMore();
that.loadDataComplete();
}
});
},
// Add Image
addImage: function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
this.$media.hide();
}
};
var myCompleteFunction = function myCompleteFunction() {}
mediaPlugin.init();
mediaPlugin.loadDataComplete = myCompleteFunction;
mediaPlugin.loadData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I finally figured how to get this code working. I used jquery .delegate() and i now work like magic. Below is the working code. thanks #abc123 for stoping by.
var media = (function(){
// Cache dom
var baseUrl = location.origin+'/dashboard/media';
var $button = $('.meidaBtn, #media_load_btn');
var $media = $('.media');
var $mediaBox = $('#mediaBox');
var $imageBox = $mediaBox.find('img');
var options = {
url: baseUrl,
type: 'GET',
success: function(data){
$mediaBox.html(data);
},
error: function(){
console.log("An error occored!");
},
complete: function(){
// console.log("I am now complete");
// that.loadMore();
}
};
// Bind Events
$button.on('click', _render);
$mediaBox.delegate('.imageBox', 'click', _addImage);
function _render(e){
e.preventDefault();
$media.show(500);
_loadData();
}
// Load images
function _loadData(){
$.ajax(options);
}
// Add Images
function _addImage(){
img = $(this).find('img');
console.log(img.attr('src')); // This should display the image url
}
})();

Ugent !!! Abort all file uploads in Blueimp jquery file upload

I am trying to upload form using BLueimp File Upload Jquery but i cannot abort all the file uploads. My configration is :
url: form.attr('action'),
type: 'POST',
datatype: 'json',
dropZone: $(document),
pasteZone: $(document),
singleFileUploads: true,
limitConcurrentUploads: 1,
And i cannot change any configration . I mean singleFileUploads : true is must.
I have also tried
xqXHr = data.submit();
But aborting it only aborts 1 file instead of all. I have been searching for 5 hourse and cannot find answer :( .
Full js code
$(document).on('click','.redbut',function(){
jqXHR.abort();
jqXHR = null;
});
$(document).bind('drop dragover', function (e) {
e.preventDefault();
});
setInterval(function(){
q=0;
$('.upf_percent').each( function(index){
q=71*index;
$(this).css('top', q + "px");
}) ;
}, 100);
$(document).ready( function() {
check_nf();
$('.direct-upload').each( function(n) {
var form = $(this);
'use strict';
form.fileupload({
url: form.attr('action'),
type: 'POST',
datatype: 'json',
dropZone: $(document),
pasteZone: $(document),
singleFileUploads: true,
limitConcurrentUploads: 1,
add: function (event, data) {
window.onbeforeunload = function() {
return 'Are you sure you want to cancel file uploads.';
};
show_ub();
$.each(data.files, function (index, file) {
var size = formatFileSize(file.size);
var filename = file.name;
var r_s = makeid(5);
file.uploadID = r_s;
$('.direct-upload').append('<div class="u_daba '+r_s+'"><div class="file_data"></div><div class="upf_percent"><div class="arrowdown">0%</div> </div><div class="progress"><div class="bar"></div></div></div>');
check_nf();
$('.'+r_s+' .file_data').html(filename+' <span class="marginL15">( '+size+' )</span><span class="floatRight marginR30 blue"><i>Pending</i></span>');
n++;
});
jqXHR = data.submit();
},
progress: function(e, data){
$.each(data.files, function (index, file ) {
var p = Math.round((data.loaded / data.total) * 100);
var r_s = file.uploadID;
$('.'+r_s+' .progress .bar').css('width', p + '%');
$('.'+r_s+' .upf_percent').html('<div class="arrowdown"></div>'+p + '%');
if(p>0){
$('.'+r_s+' .upf_percent').css('display', "block");
$('.'+r_s+' .file_data span:nth-of-type(2)').text('Uploading');
$('.'+r_s+' .file_data span:nth-of-type(2)').addClass('green');
$('.'+r_s+' .file_data span:nth-of-type(2)').removeClass('blue');
}
t = 0.9537*p + 1.13;
$('.'+r_s+' .upf_percent').css('left', t + "%");
});
},
fail: function(e, data) {
// Remove 'unsaved changes' message.
window.onbeforeunload = null;
$.each(data.files, function (index, file ) {
var r_s = file.uploadID;
$('.'+r_s+' .progress .bar').css('width', '100%').addClass('red');
$('.'+r_s+' .upf_percent').css('display', "none");
$('.'+r_s+' .file_data span:nth-of-type(2)').text('Error: '+data.errorThrown);
$('.'+r_s+' .file_data span:nth-of-type(2)').addClass('red');
$('.'+r_s+' .file_data span:nth-of-type(2)').removeClass('green');
});
},
done: function (event,data){
$.each(data.files, function (index, file ) {
var r_s = file.uploadID;
$('.'+r_s+' .file_data span:nth-of-type(2)').text('Uploaded Successfully !!');
$('.'+r_s+' .upf_percent').css('display', "none");
});
},
stop: function (event, data) {
window.onbeforeunload = null;
hide_ub();
get_fffi();
}
});
});
});
$(document).on('click','.uploadbut',function(){
$('.direct-upload #file').click();
});

Bypass Input FIle; Uploading Image directly using javascript

I'd like to automate the uploading of images to a website. The problem is I'm stuck at the input file type. The site seems to use a JQuery uploading method. I'd like to feed the script the image data directly satisfying validation.
Here's the HTML of the input file type used to upload images along with it's structure.
<div id="item_img_msg1" abp="568"></div>
<div class="mg_b5 mg_l10" id="item_img_empty1" abp="569">
<input name="updfile1" class=" " id="item_img_file1" type="file" abp="570">
</div>
<div class="mg_b5 mg_l10" id="item_img_selected1" style="display: none;" abp="571">
<img id="item_img1" src="/common/images/noimage.gif" abp="572">
<input id="item_img_del1" style="vertical-align: bottom;" type="button" value="Delete" abp="573">
</div>
<input name="hdnImgDelFlg1" id="imgdelflg1" type="hidden" value="" abp="574">
<span class="font_85 pg_l10" abp="575">(Sizeļ¼šUnder 1MB;Format:JPEG,GIF,PNG</span>
<br abp="576">
<span class="pg_l10" abp="577">Wide or Tall images will be chopped</span>
<div class="HelpTxt mg_t5" abp="578">
Guide:Image Upload Guide
</div>
And here's the related javascript.
var ImageUploader = function (idx) {
var postData = {
name: "updfile",
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var deleteData = {
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var onIamgeUploaded = function (response) {
var status = $(response).find("otoma_status").text();
if (status != "0") {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed</div>");
return;
}
var url = $(response).find("img_url").text();
$("#item_img" + idx).attr("src", url + "?" + new Date().getTime());
$("#item_img_empty" + idx).hide();
$("#item_img_selected" + idx).show();
$("[name='hdnImgDelFlg" + idx + "']").val("0");
postData.postCnt++;
};
this.manualUpload = function (data) {
var postDataForManual = $.extend({}, postData, data);
jQuery.ajax({
data: postDataForManual,
url: "/api/itemimage/upload",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
var loading_image_tag = $("<img>").attr({
"class": "js-loading_image" + idx,
src: Module.imgpath + "/lib/fileuploader/loading.gif"
});
$("#item_img_empty" + idx).after(loading_image_tag);
$("#item_img_empty" + idx).hide();
},
success: function (response) {
onIamgeUploaded(response);
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
$("#item_img_empty" + idx).show();
},
complete: function () {
$("img.js-loading_image" + idx).remove();
}
});
};
var init = function (idx) {
postData.index = idx;
try {
new AjaxUpload("#item_img_file" + idx, {
action: "/api/itemimage/upload",
name: "updfile",
data: postData,
onSubmit: function (file, extension) {
AjaxUtils.loading(true);
$("#item_img_msg" + idx).html("");
},
onComplete: function (file, response) {
AjaxUtils.loading(false);
onIamgeUploaded(response);
}
});
} catch (e) {}
$("#item_img_del" + idx).click(function () {
jQuery.ajax({
dateType: "xml",
data: deleteData,
url: "/api/itemimage/delete",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
deleteData.postCnt = postData.postCnt;
$("#item_img_msg" + idx).html("");
$("#item_img_empty" + idx).show();
$("#item_img_selected" + idx).hide();
$("[name='hdnImgDelFlg" + idx + "']").val("1");
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
}
});
});
};
init(idx);
};
var ImageUploaders = [];
var maxImageNumber = $("#max_image_number").val();
for (var i = 1; i <= maxImageNumber; i++) {
ImageUploaders.push(new ImageUploader(i));
}
var params = Module.Utility.getParameters();
var buying_support_item_id = params.buying_support_item_id;
if (buying_support_item_id) {
ImageUploaders[0].manualUpload({
buying_support_item_id: buying_support_item_id
});
}
I can make javascript script calls to the webpage. I just basically need to know which calls to make. Does anyone know how to do this? If so, could you provide sample code.
Thanks!

Categories