Getting jsfiddle 'show image file' working - image

I've sure I'm missing something simple here, I found a suggestion on here to use jsfiddle for code to preview an image before upload: http://jsfiddle.net/LvsYc/5234/
But I can't get it to work. I'm assuming I just put the javascript in the header wrapped in tags?
Here's my code (thank you - I'm sorry if this is very similar to other questions)
<script language="javascript">
window.onload=function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#artworkshow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#artwork").change(function(){
readURL(this);
});
</script>
<img id="artworkshow" src="#" alt="Image Preview" />
<p>
<label for="artwork">Artwork</label>
<input id="artwork" name="artwork" type="file" class="inputAuto" />
Size: 700px by 260px</p>
<p>

Related

Uploading photo Spring - Ajax

I am trying to upload a photo and get a preview of the uploaded image using Spring and Ajax.
I have the following code:
<h3>File Upload</h3>
<ul>
<li>
<form id="upload-form" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="uploadfile" size="45" accept="*" />
<br>
<input id="submit-button" type="submit" value="Upload" />
</form>
</li>
<li><p>Result: <br><span id="result"></span></p></li>
</ul>
<h3>Show Image</h3>
<ui>
<li>original:<img id="image-o" src="#" alt="original image" /></li>
<li>small: <img id="image-s" src="#" alt="small image" /></li>
<li>medium: <img id="image-m" src="#" alt="medium image" /></li>
<li>large: <img id="image-l" src="#" alt="large image" /></li>
<li>extra large: <img id="image-xl" src="#" alt="extra large image" /></li>
</ui>
<script type="text/javascript">
$(document).ready(function () {
$("#submit-button").on("click", function (event) {
event.preventDefault();
// create an FormData object
var data = new FormData($('#upload-form')[0]);
// disabled the submit button
$("#submit-button").prop("disabled", true);
// post data
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "image/api/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
// shows server's response
// $("#result").text(data);
console.log("SUCCESS: ", data);
enableSubmitButton();
updateImages(data);
},
error: function (e) {
// shows server's response
// $("#result").text(e.responseText);
console.log("ERROR: ", e);
enableSubmitButton();
updateImages(e.responseText);
}
});
});
});
function enableSubmitButton() {
$("#submit-button").prop("disabled", false);
}
function updateImages(data) {
var url = 'http://localhost:9001/image/api/' + data;
$('#image-s').attr('src',url + '?size=s');
$('#image-m').attr('src',url + '?size=m');
$('#image-l').attr('src',url + '?size=l');
$('#image-xl').attr('src',url + '?size=xl');
$('#image-o').attr('src',url + '?size=o');
}
</script>
And my Java code:
#POST
#Path("/upload")
#Consumes(ExtendedMediaType.MULTIPART_FORM_DATA)
#Produces(ExtendedMediaType.APPLICATION_JSON_UTF8)
#Transactional
public ResponseEntity<Void> uploadImage(#RequestParam("uploadfile") MultipartFile file) {
if (file.getSize() < maxFileSize && validExtensions.contains(file.getContentType())) {
Image image = Image.builder().id(file.getSize()).build();
imageServiceConfigMapper.saveImage(image);
/* FormDataContentDisposition fileDetail = null;
ImageMetadata imageMetadata = buildImageMetadata(fileDetail, image);
imageServiceConfigMapper.saveMetadata(imageMetadata);*/
}
return new ResponseEntity<>(HttpStatus.OK);
When I choose a photo from my PC, it is accepted - see screenshot below:
When I click in upload, my browser gives the following answer:
The JSON looks like this:
BUT the selected picture is not showing:
Am I using a wrong URL?
The address of the site where I got the above screen ends is the one with index.html at the end, but I defined /api/upload as a relative path...
If I open the relative path, I got the following:
Or is it something wrong with the code responsible for the preview?
Sorry, I know there is a tones of similar issues but I could not found anything that hepled. I am quite a beginner...
Sorry for the long post and thanks for the help in advance!
Spring Content can do this and has a getting started guide and git repo with an angularjs based front-end that demonstrates exactly what you are trying to do. The getting started guide is here.

Grails, sorting and filtering a grid at the same time using ajax

I have a grid(html-table) with a lot of columns and want to combine filtering and sorting on this table.
At the moment I only use filtering on one column but sorting on several columns.
I want to do this with ajax.
I read an article [http://www.craigburke.com/2011/01/23/grails-ajax-list-with-paging-sorting-and-filtering.html]
and tried to adapt it to my version of grails-3.2.6.
This has been very hard to solve and now I'm totally stuck.
If I add something in the filter nothing happens but when I click on a column, the filtering takes place and also sorting, clicking a second time, ajax is not called and the filter is overwritten with the default value. I have managed to implement it on a test project which act the same.
It is much code and maybe there is a way to include the whole project in this question in some way?
I'll try to show most of the important part here if it could help.
The index.gsp:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'person.label', default: 'Person')}" />
<title><g:message code="default.list.label" args="[entityName]" /></title>
<script type="text/javascript">
$(document).ready(function() {
setupGridAjax();
setupFilterAjax();
});
</script>
<script type="text/javascript">
function setupGridAjax() {
$('#gridPersons').find('.paginateButtons a, th.sortable a').on('click', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var grid = $(this).parents("table.ajax");
$(grid).html($("#spinner").html());
$.ajax({
type: 'GET',
url: url,
data: [tag],
success: function(data) {
$(grid).fadeOut('fast', function() {$(this).html(data).fadeIn('slow');});
}
})
});
}
</script>
<script type="text/javascript">
// Turn any input changes or form submission within a filter div into an ajax call
function setupFilterAjax(){
alert('FILTER--Anropat');
$('div.filters select:input').on('change',function(event) {
var filterBox = $(this).parents("div.filters");
filterGrid(filterBox);
});
$("div.filters form").submit(function() {
var filterBox = $(this).parents("div.filters");
alert('FILTERBOX - '+filterBox);
filterGrid(filterBox);
return false;
});
}
// Reload grid based on selections from the filter
function filterGrid(filterBox) {
alert('FILTER-change detected');
var grid = $(filterBox).next("div.gridPersons");
$(grid).html($("#spinner").html());
var form = $(filterBox).find("form");
var url = $(form).attr("action");
var data = $(form).serialize();
alert('FILTERGRID - '+url);
$.ajax({
type: 'POST',
url: '${g.createLink( controller:'person', action:'index' )}',
data: [tag],
success: function(data) {
$(grid).fadeOut('fast', function() {$(this).html(data).fadeIn('slow');});
}
});
}
</script>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
</ul>
</div>
<div id="list-person" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<div class="filters">
<g:form action="register">
<div id="selectMill">
Select tags:
<g:select class="selected" name="tag" from="${tagList}" value="${filters?.tag}" noSelection = "${['':'All']}" optionValue="" optionKey="" />
</div>
<div id="gridPersons">
<g:render template="Grid_Persons" model="personList" />
</div>
<div class="pagination">
<g:paginate total="${personCount ?: 0}" />
</div>
<fieldset class="buttons">
<input class="save" type="submit" value="${message(code: 'offer.create.from.buffer.label', default: 'Create')}" />
</fieldset>
</g:form>
</div>
</div>
</body>
The template: _Grid_Persons.gsp
<table class="ajax">
<thead>
<tr>
<g:sortableColumn property='reg' title='Register' />
<g:sortableColumn property="id" title='Id' params="${filters}"/>
<g:sortableColumn property='name' title='Name' params="${filters}"/>
<g:sortableColumn property='tag' title='Tag' params="${filters}"/>
<g:sortableColumn property='registered' title='Registered' params="${filters}"/>
</thead>
<tbody>
<g:each in="${personList}" status="i" var="ps">
<tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
<td><g:checkBox name="ckb" value="${ps.id}" checked="false" /></td>
<td><g:link action="edit" id="${ps.id}">${ps.id}</g:link></td>
<td>${ps.name}</td>
<td>${ps.tag}</td>
<td>${ps.registered}</td>
<td>
</g:each>
</tbody>
The index-part of the controller:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def tagList = Person.withCriteria {
projections {
distinct("tag")
}
}
def List<Person> personList = getPersonList()
// Paging def prodBuffer = getPaginatedList(prodBuffer, max, params.offset?.toInteger())
def filters = [tag: params.tag, sort: params.sort, order: params.order]
def model = [personList: personList, filters:filters, tagList:tagList]
if (request.xhr) {
println("AJAX-Request!!!")
render(template:"Grid_Persons", model:model)
prodBuffer, offerDetails:offerDetails, filters:filters])
} else {
offerDetails: offerDetails, millList: millList, selectedMill:false, prodBufferCount: ProdBuffer.count()]
[personList:personList,tagList:tagList]
}
Person.count(), tagList:tagList]
}
def List<Person> getPersonList() {
println("getPersonList tag: "+params.tag)
def tag = params.tag
def c = Person.createCriteria()
def tempList = c.list {
if (tag) eq("tag", tag)
if (params.sort){
order(params.sort, params.order)
}
}
return tempList
}
From debugging:
The page is loaded:
getPersonList tag: null
Selected "Grails" in the filter:
getPersonList tag: Grails
AJAX-Request!!!
Klicked on the "Name"-column header
getPersonList tag: Grails
AJAX-Request!!!
-- Now the list is sorted(ascending) and filtered
Klicked on the column again:
getPersonList tag: Grails
-- Now the list is resorted(descending) and the filtering still ok but the SELECT TAGS now view "All"
Klicked the column for the third time:
getPersonList tag:
AJAX-Request!!!
-- Now the list show all lines and resorted(ascending)
Now solved by using the recommended plugin - datatables.
In case you are in a hurry you can inject https://datatables.net/ that adds the utilities you require among others

How to add google reCAPTCHA in the newsletter form in magento?

How to add google reCAPTCHA with the newsletter in magento to stop receiving newsletter emails in the spam.
Add the below code in the "form file" under the form tag to resolve your query.
<div class="recaptcha" style="overflow:hidden;position:relative;">
<input type="checkbox" id="recaptcha-verification-1" name="recaptcha-verification-1" value="" class="hide required-entry" style="visibility:hidden;position:absolute;left:-1000000px" />
<div id="recaptcha-1"></div>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('recaptcha-1', {
'sitekey': "6Lf9tBcTAAAAAEbCd2XlhPGH3o850Qp9ZMJJ2fr2",
'theme': "light",
'callback': function(response) {
if (response.length > 0) {
$('recaptcha-verification-1').writeAttribute('value', 'checked');
$('recaptcha-verification-1').checked = true;
}
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en" async defer></script></div>
I was facing the same issue and I made it solved one extension "Google Invisible reCaptcha"
Wait... I changed few modifications in JS code also.
After installing extension set Site key and secret in admin side and open subscription.phtml
YOUR-PROJECT/app/design/frontend/YOURTHEME/default/template/newsletter/subscribe.phtml
Add code just after Form Tag.
<div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY"></div>
In the last of file add this JS Snippet.
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#recaptcha_response_field').addClass('required-captcha-entry');
})
var yourFormValidationObj = new VarienForm('newsletter-validate-details');
Validation.add('required-captcha-entry', ' ', function(v) {
return !Validation.get('IsEmpty').test(v);
})
</script>
It worked for me. Cheers if it works for you..

Input Button as Input image will not work

On my website i have a button which when clicked takes you to one of two random youtube videos. However i would like to change this to a image in stead of a button.I have tried to change it to a INPUT type="image" but this doesn't work. Here is the code i am using.
<SCRIPT language="JavaScript">
<!--
function get_random()
{
var ranNum= Math.floor(Math.random()*2);
return ranNum;
}
function getaGame()
{
var whichGame=get_random();
var game=new Array(2)
game[0]= "https://www.youtube.com/watch?feature=player_detailpage&v=NcFQF3PZFRk#t=722s";
game[1]= "https://www.youtube.com/watch?v=klBAW4MQffU";
location.href = game[whichGame];
}
//-->
</SCRIPT>
<FORM name="form1">
<center>
<INPUT type="button" onClick="getaGame()" >
</center>
</FORM>
Thanks for any help
An onclick event can be fired from any element. Here are some examples!

Events not working when using Mustache with Backbone.js

So I am making a test app using RequireJs, Mustache and Backbone.js. I had some success with rendering the collection of models with the Mustache template. But my Mustache template has a button and when I try to bind click event on the button in the view, the button click doesn't invoke the callback function. I am really stuck, can someone tell me where I am not doing right?
Here is my code:
ItemView.js:
define(['jquery', 'backbone', 'underscore', 'mustache', '../../atm/model/item'], function ($, Backbone, _, Mustache, Item) {
var ItemView = Backbone.View.extend({
initialize: function() {
},
tagName: 'li',
events: {
'click .button': 'showPriceChange'
},
render: function() {
var template = $('#template-atm').html();
var itemObj = this.model.toJSON();
itemObj['cid'] = this.model.cid;
var rendering = Mustache.to_html(template, itemObj);
this.el = rendering;
return this;
},
showPriceChange: function(event) {
alert('Changing...');
$('#' + elemId).empty();
$('#' + elemId).append(document.createTextNode('Changed'));
},
});
return ItemView;
});
atm.html:
<!DOCTYPE html>
<html>
<head>
<title>Elevator</title>
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<style type="text/css">
</style>
</head>
<body>
<h1>Vending Machine</h1>
<div id="atm-items">
</div>
<script id="template-atm" type="html/template">
<li>
<p>Item: {{name}}</p>
<label for="price-{{cid}}">Price:</label>
<input id="price-{{cid}}" type="text" value="{{price}}"/>
<button class="button">Change</button>
<p id="status-{{name}}-{{cid}}">- -</p>
</li>
</script>
</body>
</html>
You're replacing the view's el inside render:
render: function() {
//...
this.el = rendering;
//...
}
When you do that, you're losing the jQuery delegate that is attached to this.el, that delegate handler (which Backbone adds) is responsible for the event routing.
Usually, you add things to this.el rather than replacing this.el. If your template looked like this:
<script id="template-atm" type="html/template">
<p>Item: {{name}}</p>
<label for="price-{{cid}}">Price:</label>
<input id="price-{{cid}}" type="text" value="{{price}}"/>
<button class="button">Change</button>
<p id="status-{{name}}-{{cid}}">- -</p>
</script>
then you would this.$el.append(rendering) in your view's render; this would give you an <li> in this.el since you've set your view's tagName to li.
Alternatively, if you really need to keep the <li> in the template, you could use setElement to replace this.el, this.$el, and take care of the event delegation:
this.setElement(rendering);
Presumably you're wrapping all these <li>s in a <ul>, <ol>, or <menu> somewhere else; if you're not then you're producing invalid HTML and the browser might try to correct it for you, the corrections might cause you trouble elsewhere as your HTML structure might not be what your selectors think it is.

Resources