use dropzone.options without form - javascript

I want to use dropzone on with id. But my Dropzone.options.myid={}
is not working. How to validate file type, size in
var myDropzone = new Dropzone("div#myid", { url: "/file/post"});
I cant use tag
console.log file is not working why?
My source:
<div id="myid" style="width: 500px; height: 300px; border: 1px solid black">click here</div>
javascript
var myDropzone = new Dropzone("div#myid", { url: "dropzoneupload"});
Dropzone.options.myid = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
accept: function(file, done) {
console.log(file);
if (file.name == "justinbieber.jpg") {
done("Naha, you don't.");
}
else { done(); }
}
};

I don't see where are you using dropzone class to define your dropzone area, does it generate you the default dropzone?
<div id="myDropZone" class="fallback dropzone" enctype="multipart/form-data">
<input type="file" id="files" class="display" multiple />
</div>
First you need to detach the default dropzone, add this out of you document ready load.
Dropzone.autoDiscover = false;
Then you jquery or js
var $myDropZone;
$myDropZone= new Dropzone('div#myDropZone', {*all your settings*
addRemoveLinks: true, //to remove
dictRemoveFile: '<i class="fa fa-times-circle" style="font-weight: 900;
cursor:pointer;"></i>' //I used an icon and styled as button so to give a user
experience to remove it});
Hope it helps, regards.

Related

Displaying a loading gif every time when a date picker date is changed

I have a laravel application which shows some stats to my users.
On my front end blade, I'm displaying few widgets where each widget contain's a specific stat.
Following widget is to show number of total orders.
<div class="row mt-3" id="shopify_row1">
<div class="col-md-2" id="shopify_widget1">
<div class="jumbotron bg-dark text-white">
<img class="img-fluid pull-left" src="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png" width="32" height="32">
<h6 class="text-secondary mt-2 px-4">Shopify</h6>
<hr class="border border-white">
<h5 class="text-white">Total Orders</h5>
<span class="tot_o" id="tot_o">{{ $tot_o }}</span>
</div>
</div>
</div>
Like this widget, I have 5 more widgets to display 5 different stats.
In every widget initially I'm displaying stats for the current date, eg: if the total number of orders for the day is 0, it shows 0...
Then, I have added a a date picker as I can get the data only for a particular day.
<td>
<input id="date" class="date form-control" type="date">
</td>
And following is my jQuery...
<script>
$(document).on('change', '#date', function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
url : '/shopify_data',
data : {selected_date : $('#date').val()},
success:function(data){
$('#tot_o').empty();
$('#tot_sum').empty();
$('#avg_ov').empty();
$('#cus').empty();
$('#item_sum').empty();
$('#orders').empty();
var total_orders = data.tot_o;
var total_sales = data.sum;
var currency = data.crr;
var avg_ov = data.avg_ov;
var cus = data.cus;
var item_sum = data.item_sum;
var orders = data.orders;
$('#tot_o').append(total_orders);
$('#tot_sum').append(total_sales);
$('#avg_ov').append(avg_ov);
$('#cus').append(cus);
$('#item_sum').append(item_sum);
$('#orders').append(orders);
//console.log(total_orders);
},
timeout:10000
});
});
</script>
This entire code works perfectly, but now I need to add a loading gif till the updated results get displayed on the date change.
What changes should I do to above jQuery in order to add the loading gif...
There are multiple ways how you can create the loading gif. One would be to create an element in your blade template that is hidden or shown by using a class.
HTML:
<div class="loader hidden"></div>
CSS:
.hidden {
display: none;
}
jQuery:
const loader = document.querySelector('.loader');
$(document).on('change', '#date', function (e) {
loader.classList.remove('hidden');
// your other code..
}
And inside your success function you add the hidden class which should hide the loading element again.
success: function(data){
loader.classList.add('hidden');
// your existing code..
},
However, I would instead add a complete block, which ensures that on failure as on success the loading element is hidden.
$.ajax({
// your existing code..
complete: () => {
loader.classList.add('hidden');
}
}
You can place loading gif in any place of DOM with style="display: none".
Next, in your script before ajax you can show gif and after success or fail result hide it again:
<script>
let gif = $('.loading-gif'); // Your loading gif
$(document).on('change', '#date', function (e) {
gif.show(); // Show loading gif
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
url : '/shopify_data',
data : {selected_date : $('#date').val()},
success:function(data){
gif.hide(); // Hide gif
$('#tot_o').empty();
$('#tot_sum').empty();
$('#avg_ov').empty();
$('#cus').empty();
$('#item_sum').empty();
$('#orders').empty();
var total_orders = data.tot_o;
var total_sales = data.sum;
var currency = data.crr;
var avg_ov = data.avg_ov;
var cus = data.cus;
var item_sum = data.item_sum;
var orders = data.orders;
$('#tot_o').append(total_orders);
$('#tot_sum').append(total_sales);
$('#avg_ov').append(avg_ov);
$('#cus').append(cus);
$('#item_sum').append(item_sum);
$('#orders').append(orders);
//console.log(total_orders);
},
timeout:10000
});
});
</script>

How to capture the id of a div on click and pass it to the function to make the code dynamic?

I have a coffeescript based code which has all the definitions (IDs and Classes) are called locally. Now I want it to refactor it based on a dynamic view i.e, on click by the user in the site, that should send the corresponding ID to the function. How do I deal with this?
HTML -
<div id="dl1">
<div class="dl_div">
<div id="target1" data-key="<%= #aws_url1[:key] if !#aws_url1.nil? %>">
<% if !#aws_url1.nil? %>
<img id="user_dl1" src="<%= #aws_url1[:url] %>">
<% end %>
</div>
<div id="close1" style="display: none;">
<button id="closebtn1" class="closebtn">X</button>
</div>
<div id="closemsg1" style="display: none; position: relative;">
<button id="deletebtn1" class="deletebtn">
<p class="deletebtnstyle">Delete</p>
</button>
<button id="cancelbtn1" class="cancelbtn">
<p class="cancelbtnstyle">Cancel</p>
</button>
</div>
<div class="file_browser1" id="file_browser1">
<label for="file_upload1" class="custom-file_upload z-depth-1">
<i class="material-icons"></i>
<p class="button-text"> Upload Here</p>
</label>
<form id="user_id1_form" action="">
<input type="hidden" name="user_id1_key" value="<%= #aws_urls[0][:key] %>"/>
<input id="file_upload1" type="file" accept="image/*" name="user_id1"/>
</form>
</div>
</div>
</div>
CoffeeScript -
if $('#target1 img').length == 1
$('#file_browser1').addClass 'none'
$('#close1').addClass 'delete'
$('#closebtn1').on 'click', (e) ->
$('#closemsg1').addClass 'msg'
$('#cancelbtn1').click ->
$('#closemsg1').removeClass 'msg'
$('#deletebtn1').click ->
$('#close1').removeClass 'delete'
$('#closemsg1').removeClass 'msg'
$('#target1 > img').hide()
$('#file_browser1').removeClass 'none'
$('#file-upload1').val('')
return
$('#file_upload1').on 'change', (event) ->
files = event.target.files
image = files[0]
old_key = $("#target1").data("key");
new_key = null
$user_id1 = $('#file_upload1')[0].files[0];
console.log image.size
reader = new FileReader
$.ajax({
type: "GET",
url: "http://localhost:3000/users/get_url/13",
success :(data) ->
new_key = data[0].key
processfile $user_id1,(result)->
console.log data[0].url
$user_id1 = dataURItoBlob(result)
reader1 = new FileReader()
reader1.readAsArrayBuffer($user_id1)
reader1.onload = (e) ->
rawData1 = reader1.result;
$.ajax({
url: data[0].url,
type: 'PUT',
xhr: ->
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload)
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
return myXhr;
,
success: completeHandler,
error: errorHandler,
data: rawData1,
cache: $.param(false),
contentType: "binary/octet-stream",
processData: $.param(false)
}, 'json');
})
completeHandler = (data) ->
$.ajax({
type: "POST",
url: "http://localhost:3000/users/user_documents/13",
data: {
aws_key_new: new_key,
aws_key_old: old_key,
dl_id: "dl",
},
success: ->
a = $('#target1')
console.log a.data("key")
console.log new_key
a.attr('data-key', new_key);
})
success :(data) ->
alert "complete"
return
error :(data) ->
alert "failed"
return
errorHandler = (data) ->
console.log data
alert "failed"
progressHandlingFunction = (data) ->
reader.onload = (file) ->
img = new Image
img.src = file.target.result
$('#target1').html img
$('#file_browser1').addClass 'none'
$('#close1').addClass 'delete'
$('#closebtn1').on 'click', (e) ->
$('#closemsg1').addClass 'msg'
$('#cancelbtn1').click ->
$('#closemsg1').removeClass 'msg'
$('#deletebtn1').click ->
$('#close1').removeClass 'delete'
$('#closemsg1').removeClass 'msg'
$('#target1 > img').hide()
$('#file_browser1').removeClass 'none'
$('#file-upload1').val('')
return
return
reader.readAsDataURL image
console.log files
return
How to pass the IDs to the coffeescript on click?
If I understood from your question, you want to adding click events to a group of elements and be able to get their respective values when trigged.
One way to do it would be to adding click event to the attribute class:
For example (using jquery):
// Add click event to the class .drill_cursor
$(".drill_cursor").click(function(){
console.log(this.id);
});
// Used to display console.log
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function (text) {
$("#console-log").append($(consoleLine).html(text));
}
};
.console-line {
font-family: monospace;
color: red;
margin: 2px;
}
.drill_cursor {
margin: 50px;
color: blue;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="console-log"></div>
<div id="id-div-1" class="drill_cursor" >div-1-click-on-me</div>
<div id="id-div-2" class="drill_cursor" >div-2-click-on-me</div>
<div id="id-div-3" class="drill_cursor" >div-3-click-on-me</div>
<div id="id-div-4" class="drill_cursor" >div-4-click-on-me</div>
</body>
Another way to do it would be delegating the event to another element tag:
You can find more information about delegate events here:
api.jquery.com/delegate
For some cases, delegate events is a better way to add events dynamically!
I hope it helps you!
Good luck!

HTML5 Image Preview Not Working On Cloned File Input (Does on Original)

What I am trying to do is have a modal form which contains a file input along with various other form fields, then, once the modal form is submitted, the file input, as well as other form elements, are then moved to the main form I want to eventually submit and I then reset the form and replace the original file input with a clone of the original in order to accept further entries.
Everything works perfectly fine except that the html 5 image preview doesn't work on any cloned file inputs, so it only works on the original file input that's present on page load and not any subsequent inputs.
I've tried changing the event handler as well as recalling handleImages once the clone is added to the DOM but neither seemed to make a difference and I can't think of what to try next.
I've made a codpen and the code is also below:
HTML
<div class="container">
<form action="" class="form-inline" id="image-form">
<label class="btn btn-info upload-button">
Tap to Select Images
<input type="file" style="display: none" multiple accept="image/*" capture="camera">
</label>
<button type="button" class="btn btn-primary" id="save-image">Save Images</button>
<div class="preview">
<div class="row">
</div>
</div>
</form>
<div id="saved-images" style="display: none;"></div>
</div>
JS
var imageCount = 0;
var ImageUpload = function() {
var handleImages = function() {
document.querySelector('#image-form input[type="file"]').addEventListener('change', handleFileSelect, false);
// also tried
// $(document).on('change', '#image-form input[type="file"]', handleFileSelect);
}
var handleFileSelect = function(e) {
if ( !e.target.files || !window.FileReader) return;
var $element = $(e.srcElement).closest('form').find('.preview > .row');
$element.empty();
var $srcElement = $(e.srcElement);
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if (!f.type.match("image.*")) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var html = `
<div class="col-lg-3 col-md-4 col-xs-6 thumbnail m-t m-b m-r m-l">
<img class="img-responsive" src="${e.target.result}" alt="${f.name}">
<div class="title bg-success">${f.name}</div>
</div>
`;
$element.append(html);
}
reader.readAsDataURL(f);
});
}
var handleSaveImage = function() {
$(document).on('click', '#save-image', function(f) {
// Clone the "real" input element
var $real = $('#image-form input[type="file"]');
var $clone = $real.clone(true);
/* Also tried:
var $clone = $real.clone(false);
handleImages();
and
var $clone = $real.clone(true).val('');
*/
// Put the cloned element directly after the real element
$clone.insertAfter($real);
// change the name and class of the real input
$real.addClass(`image-${imageCount}`);
// Move the real element
$real.appendTo('#saved-images');
imageCount++;
resetImageForm();
});
}
var resetImageForm = function() {
$('#image-form').trigger('reset');
$('#image-form .preview').empty();
}
return {
// main function to initiate the module
init: function() {
handleImages();
handleSaveImage();
}
};
}();
jQuery(document).ready(function() {
ImageUpload.init();
});
If I change the event listener to $(document).on('change', '#image-form input[type="file"]', handleFileSelect); then the preview code is reached every time but there's no preview, here's a forked version to show what I mean enter link description here
I seen your code and here is solution
jsfiddle
use $(e.target) instead of $(e.srcElement)

Ajax form submit twice when include jcarousel script

I'm using Ajax to submit my form, but when i click button Add to cart the form will submit twice but if i remove jcarousel , the form will submit like normal.
<form id="formrandom1473" name="formrandom1473" method="post" action="ajax_process.php?case=add_product_ajax&pid=1473">
<input type="hidden" value="1473" name="products_id">
<input type="hidden" value="1" name="qty">
<div class="add_to_cart_div">
<input type="image" border="0" id="add-to-cart-1473" title=" Add to Cart " alt="Add to Cart" src="includes/languages/english/images/buttons/button_in_cart.gif">
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#add-to-cart-1473").click(function () {
var formrandom1473 = $("#formrandom1473");
formrandom1473.submit(function () {
$.ajax({
type: formrandom1473.attr("method"),
url: formrandom1473.attr("action"),
data: formrandom1473.serialize(),
success: function (data) {
$("#output").html(data);
$(".message_div").addClass("message_success").slideDown().delay(6000).slideUp(); // Div success
$(".cart_counter").load("ajax_process.php?case=cart_counter"); // Load new quantity / by quantity
$(".shopping_cart_box").load("ajax_process.php?case=shopping_cart_box"); // Load new shopping cart box / by product
$(".cart_dropdown").load("ajax_process.php?case=cart_dropdown"); // Load new shopping cart box / by product
}
});
$("formrandom1473").unbind();
return false;
});
/* Effect */
var productX = $("#cart-image-1473").offset().left;
var productY = $("#cart-image-1473").offset().top;
var basketX = $("#boxcart-content").offset().left;
var basketY = $("#boxcart-content").offset().top;
var gotoX = basketX - productX;
var gotoY = basketY - productY;
var newImageWidth = $("#cart-image-1473").width() / 3;
var newImageHeight = $("#cart-image-1473").height() / 3;
$("#wrapper").html("");
$("#wrapper").css({"position":"absolute","top": productY,"left": productX});
$("#cart-image-1473").clone()
.prependTo("#wrapper")
.css({"position" : "absolute", "border" : "1px dashed black"})
.animate({opacity: 0.6})
.animate({opacity: 0.0, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200,
function() {
});
/* Effect */
}); //click
}); //ready
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.mycarousel').jcarousel();
});
</script>
i tried to use $("formrandom1473").unbind(); but the problem still same.
Did you mean to use $("#formrandom1473").unbind(); with the # instead?
Or, since you already stored the jQuery object earlier:
formrandom1473.unbind();
If unbind doesn't work for you, try this instead, but move it BEFORE the $.ajax:
formrandom1473.submit(function() { return false; });
Also, check your JS console for any errors.
After refer this comment .. the form finally can submit like normal after i'm using e.stopImmediatePropagation();
formrandom1473.submit(function (e) {
$.ajax({
type: formrandom1473.attr("method"),
url: formrandom1473.attr("action"),
data: formrandom1473.serialize(),
success: function (data) {
$("#output").html(data);
$(".message_div").addClass("message_success").slideDown().delay(6000).slideUp(); // Div success
$(".cart_counter").load("ajax_process.php?case=cart_counter"); // Load new quantity / by quantity
$(".shopping_cart_box").load("ajax_process.php?case=shopping_cart_box"); // Load new shopping cart box / by product
$(".cart_dropdown").load("ajax_process.php?case=cart_dropdown"); // Load new shopping cart box / by product
}
});
e.stopImmediatePropagation();
return false;

How can I use Multi Media Uploader in the WordPress Plugins?

I try to add the multi uploading options in the wordpress plugins I repeated this code in the plugin(two times) only changing the id name.
<script language="JavaScript">
jQuery(document).ready(function($) {
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#upload_image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery('img', html).attr('src');
jQuery('#upload_image').val(imgurl);
tb_remove();
};
});
</script>
<input id="upload_image" style=" margin-left:303px;" type="text" size="36" name="upload_image_template" value="<?php echo get_option('upload_image_template'); ?>" />
<input id="upload_image_button" type="button" value="Browse" />
Whenever I try to upload a image that media frame comes and the uploading process are did successfully. But Insert Into Post fetch the correct url but pasted in different input box.
For example:
1) [text box1] [browse Button]
2) [text box2] [browse button]
When I upload image with Text Box One that [insert post] that image path is shown in [text box 2]
I am Not Sure Whether the Problem is mine or that script didn't support multi file upload option.
Here is the example how you can use the wordpress multimedia uploader for more than one field or as many fields. The JS code and html code looks like this
How it works
Add upload_image_button class on each upload button on the basis of this class click function triggers to fetch the wordpress multimedia uploader , see i have used the prev() property to get the previous element to the clicked one formfieldID=jQuery(this).prev().attr("id"); and then i have assigned the image url returned by uploader to formfieldID
<input id="upload_image1" type="text" name="upload_image1" value="<?php echo $upload_image1;?>" />
<input class="upload_image_button" type="button" value="Upload image 1" />
<input id="upload_image2" type="text" name="upload_image2" value="<?php echo $upload_image2;?>" />
<input class="upload_image_button" type="button" value="Upload image 2" />
<script type="text/javascript">
//tb_show('', 'media-upload.php?TB_iframe=true');
var upload_image_button=false;
jQuery(document).ready(function() {
jQuery('.upload_image_button').click(function() {
upload_image_button =true;
formfieldID=jQuery(this).prev().attr("id");
formfield = jQuery("#"+formfieldID).attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
if(upload_image_button==true){
var oldFunc = window.send_to_editor;
window.send_to_editor = function(html) {
imgurl = jQuery('img', html).attr('src');
jQuery("#"+formfieldID).val(imgurl);
tb_remove();
window.send_to_editor = oldFunc;
}
}
upload_image_button=false;
});
})
</script>
Also make sure you have included the necessary JS and CSS files of the uploader for this you have to add an action
<?php
function my_admin_uploader_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload', WP_PLUGIN_URL.'/my-script.js', array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}
function my_admin_uploader_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'my_admin_uploader_scripts');
add_action('admin_print_styles', 'my_admin_uploader_styles');
?>
Note: Also take care of one thing when you assign the uploader to
you input fields the control of uploader now assigns to the fields so
when ever uploader will be called it assigns the image url to your
text field , so this is the problem when you triggers the uploader you
are unable to insert the images in the content area of the post for
this solution you have to store the previous control in some where and
when you are done with uploader then reassign the control of uploader
to the previous function which i have provided in my JS code see below
how it works
var oldFunc = window.send_to_editor;
window.send_to_editor = function(html) {
imgurl = jQuery('img', html).attr('src');
jQuery("#"+formfieldID).val(imgurl);
tb_remove();
window.send_to_editor = oldFunc;
}
I have used this technique many times and it works perfect for me
Hope it makes sense
Here, for the edit image to work, also to show other filter, hope it helps.
pa_uploader = wp.media({
title: 'Choose Images',
multiple: true,
//frame: 'select',
library: {
filterable: 'all',
editable: true,
contentUserSetting: false
},
states: [
new wp.media.controller.Library({
id: 'library',
title: 'Select Images',
priority: 40,
// toolbar: 'gallery',
filterable: 'all',
multiple: 'add',
editable: true,
contentUserSetting: false,
library: wp.media.query( _.defaults({
type: 'image'
}, {} ) )
}),
new wp.media.controller.EditImage({model: {}})
]
});
// pa_uploader.states.add([
// new wp.media.controller.EditImage({model: {}})
// ]);
pa_uploader.on('content:render:edit-image', function() {
var controller = pa_uploader.modal.controller;
image = pa_uploader.state().get('image'),
view = new wp.media.view.EditImage( { model: image, controller: controller } ).render();
pa_uploader.content.set( view );
// after creating the wrapper view, load the actual editor via an ajax call
view.loadEditor();
});
pa_uploader.on('select', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var selected_images = pa_uploader.state().get('selection');
});
});
});
The answer from M Khalid Junaid is great but outdated.
See the codex page about wp.media : https://codex.wordpress.org/Javascript_Reference/wp.media.
Here is my code based on Codex wp.media Example
Javascript
var sfieldGroup= '.field-group'; // top level parent
var wpMediaUploader = {
sBtnAdd : ".upload-custom-wp-media",
sBtnRemove : ".remove-custom-wp-media",
sMediaData: ".media-data",
sInput : ".custom-wp-media"
};
function wpMedia() {
$(wpMediaUploader.sBtnAdd).on("click", function (event) {
event.preventDefault();
var self = $(this);
var fieldGroup = self.parents(sfieldGroup);
// Create a new media frame
var frame = wp.media({
title: "Select or Upload Media Of Your Chosen Persuasion",
button: {
text: "Use this media"
},
multiple: false // Set to true to allow multiple files to be selected
});
frame.on("select", function () {
var attachment = frame.state().get("selection").first().toJSON();
switch(attachment.mime){
case "image/jpeg" :
case "image/png" :
case "image/bmp" :
case "image/gif" :
fieldGroup.find(wpMediaUploader.sMediaData)
.append("<img src=\"" + attachment.url + "\" alt=\"\" />");
break;
}
$("<p/>",{
text: attachment.filename
}).appendTo(fieldGroup.find(wpMediaUploader.sMediaData));
fieldGroup.find(wpMediaUploader.sInput).val(attachment.id);
fieldGroup.find(wpMediaUploader.sBtnAdd).addClass("hidden");
fieldGroup.find(wpMediaUploader.sBtnRemove).removeClass("hidden");
frame.close();
});
frame.open();
});
$(wpMediaUploader.sBtnRemove).on("click", function (event) {
event.preventDefault();
var self = $(this);
var fieldGroup = self.parents(sfieldGroup);
// Clear out the preview image
fieldGroup.find(wpMediaUploader.sMediaData).html("");
// Un-hide the add image link
fieldGroup.find(wpMediaUploader.sBtnAdd).removeClass("hidden");
// Hide the delete image link
fieldGroup.find(wpMediaUploader.sBtnRemove).addClass("hidden");
// Delete the image id from the hidden input
fieldGroup.find(wpMediaUploader.sInput).val("");
});
}
HTML
<div class="field-group">
<div class="media-data"></div>
<p class="hide-if-no-js">
<a class="button upload-custom-wp-media" href="javascript:void(0)">Upload Media</a>
<a class="button remove-custom-wp-media hidden" href="javascript:void(0)">Remove Selected Media</a>
</p>
<input id="test" name="test" class="custom-wp-media" value="" type="hidden">
</div>
Tip
if you console.log frame,you will be exposed to API :)
var frame = wp.media({
title: "Select or Upload Media Of Your Chosen Persuasion",
button: {
text: "Use this media"
},
multiple: false // Set to true to allow multiple files to be selected
});
It wasn't that hard...
See this revision history to see how I did...
Basically what I did was adding this to my plugin:
function wp_gear_manager_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('jquery');
}
function wp_gear_manager_admin_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'wp_gear_manager_admin_scripts');
add_action('admin_print_styles', 'wp_gear_manager_admin_styles');
And later this part in my JavaScript file:
<script language="JavaScript">
jQuery(document).ready(function() {
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#upload_image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#upload_image').val(imgurl);
tb_remove();
}
});
</script>
And this in my html:
<tr valign="top">
<td>Upload Image</td>
<td><label for="upload_image">
<input id="upload_image" type="text" size="36" name="upload_image" value="<?php echo $gearimage; ?>" />
<input id="upload_image_button" type="button" value="Upload Image" />
<br />Enter an URL or upload an image for the banner.
</label>
</td>
</tr>
You can just copy and paste this code to your plugin and see the magic.

Categories