Check the image dimensions/size before upload - javascript

How I can check the dimensions of a image using this function? I just want to check before the upload...
$("#LINK_UPLOAD_PHOTO").submit(function () {
var form = $(this);
form.ajaxSubmit({
url: SITE_URL + 'functions/_app/execute/link_upload_photo.php',
dataType: 'html',
beforeSubmit: function () {
//CHECK DE IMAGE DIMENSIONS, SIZE, AND SHOW ERRORS
},
uploadProgress: function (event, position, total, complete) {
$(".j_progressbar").fadeIn();
$(".j_progressbar .bar").width(complete + "%");
},
success: function (data) {
$("#PHOTO_UPLOADED").css("background-image","url("+window.URL.createObjectURL(document.getElementById('ADD_FIGURE').files[0])+")");
$("#PHOTO_UPLOADED").css("background-size","462px");
$("#UPLOAD_STATUS").css("opacity", "0.5");
$("#UPLOAD_STATUS").css("-moz-opacity", "0.5");
$("#UPLOAD_STATUS").css("filter", "alpha(opacity=50)");
$(".j_progressbar").hide();
$(".ADD_FIGURE").attr("rel",data);
}
});
return false;
});
Thank you for everything.

Refer the docs for the use of .naturalWidth & .naturalWidth read-only properties of the HTMLImageElement.
var x = document.getElementById("myImg").naturalWidth;
function myFunc() {
var x = document.getElementById("myImg").naturalWidth;
var y = document.getElementById("myImg").naturalHeight;
alert(x + "X" + y);
}
<img id="myImg" src="http://www.w3schools.com/jsref/compman.gif" style="width:500px;height:98px;">
<button onclick=myFunc()>GET DETAILS</button>

Related

How to make HTML Progress Bar Correctly

I am trying to make a Progress Bar for the uploaded progress in my application. So far I have this
<div class="col-sm-12">
<span style="border-left:5px solid #555555; padding-left:.5em">Upload File</span>
<div style="margin-top:1em; margin-left:.8em;">
<input type="file" name="file" class="inputfile" id="group-agent-file" accept=".csv"/>
<label for="file" id="span-file-upload" class="btn btn-danger">
<span class="fa fa-upload" style="margin-right:.5em"></span>
<span id="span-file-name">Choose a file</span>
</label>
<div>
<button type="button" id="btn-group-agent-upload" class="btn btn-primary" title="Upload">Upload</button>
</div>
<div class="progress">
<div class="progress-bar progress-bar-green" role="progressbar" id="progress-bar-upload">
<span></span>
</div>
</div>
and this is my javascript
var result = event.target.result;
var data = $.csv.toObjects(result);
var length = data.length;
var count = 0;
var percent;
$.each(data, function (key, val) {
$.ajax({
xhr: function(){
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (evt) {
console.log('progress', evt.loaded / evt.total * 100);
};
},
type: "POST",
url: "IROA_StoredProcedures.asmx/Insert_Bulk_Agent",
data: JSON.stringify(val),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
count = count + 1;
percent = count / length * 100;
$("#progress-bar-upload").css("width", percent + "%");
$("#progress-bar-upload span").text(percent + "% Complete");
console.log("Finished " + count + " of " + length + " employees.");
},
error: function (XMLHttpRequest) {
alert("error in Insert_Bulk_AgentInfo()");
console.log(XMLHttpRequest);
}
});
});
it works fine but I think the html can't process enough that sometimes the width percentage is delayed. How can I do this? and what may be the drawbacks when I use setInterval.
To get upload progress in jQuery you need to attach Event-Listener to the progress event.
You can do something like this in jQuery
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total);
//Update the progress bar
}
});
return xhr;
},
type: 'POST',
url: "/upload/path",
data: { YOUR UPLOAD DATA },
success: function (data) {
}
});
This would work the same for plain js
var xhr = new XMLHttpRequest();
xhr.open('POST', "/upload/path", true);
xhr.upload.addEventListener('progress', function (event) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total);
//Update the progress bar
}
}
xhr.onload = function (response) {
// handle success/error here
}
xhr.setRequestHeader(SET_HEADERS);
xhr.send(UPLOAD_DATA);
success function will be call when your ajax call gets completed.
You should use xhr function instead of success.
xhr: function(){
var xhr = $.ajaxSettings.xhr() ;
xhr.upload.onprogress = function(evt){
console.log('progress', evt.loaded/evt.total*100);
var percentageCompleted = evt.loaded/evt.total*100;
updateUploadPercentage(parseInt(percentageCompleted));
if(percentageCompleted == 100){
$("#p_custom_message_body").html('<p>Storing training data</p><img src="media/images/loading.gif">');
}
} ;
return xhr ;
}
After that update progress bar in another function :-
function updateUploadPercentage(progress) {
var elem = document.getElementById("progressBar");
elem.style.width = progress + '%';
elem.innerHTML = progress * 1 + '%';
}

imagecreatefromgif() from base64 encoded animated gif in POST

I am trying to make animated GIFs from media streams, videos, or images using the GifShot plugin.
My problem is that the ajax part does not see webcam_image_ajax.php. isn't working. Please do not hate me so the question will be a little longer.
I have to create this ajax function for uploading image:
var pos = 0, ctx = null, saveCB, gif = [];
var createGIFButton = document.createElement("canvas");
createGIFButton.setAttribute('width', 320);
createGIFButton.setAttribute('height', 240);
if (createGIFButton.toDataURL)
{
ctx = createGIFButton.getContext("2d");
gif = ctx.getImageData(0, 0, 320, 240);
saveCB = function(data)
{
var col = data.split(";");
var img = gif;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 4 * 320 * 240)
{
ctx.putImageData(img, 0, 0);
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
function(data)
{
if($.trim(data) != "false")
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: $.base_url+"webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview').attr('id');
var T= M+','+values;
if(T!='undefinedd,')
$("#uploadvalues").val(T);
}
});
}
else
{
$("#webcam").html('<div id="camera_error"><b>Camera could not connect.</b><br/>Please be sure to make sure your camera is plugged in and in use by another application.</div>');
$("#webcam_status").html("<span style='color:#cc0000'>Camera not found please try again.</span>");
$("#webcam_takesnap").hide();
return false;
}
});
pos = 0;
}
else {
saveCB = function(data) {
gif.push(data);
pos+= 4 * 320;
if (pos >= 4 * 320 * 240)
{
$.post("webcam_image_ajax.php", {type: "pixel", gif: gif.join('|')},
function(data)
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: "webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview, .gifshot-image-preview-section').attr('id');
var T= M+','+values;
if(T!='undefined,')
$("#uploadvalues").val(T);
}
});
});
pos = 0;
}
};
}
};
}
$("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "js/jscam_canvas_only.swf",
onSave: saveCB,
onCapture: function ()
{
webcam.save();
},
debug: function (type, string) {
$("#webcam_status").html(type + ": " + string);
}
});
});
/**Taking snap**/
function takeSnap(){
webcam.capture();
}
You can see this code in my ajax function:
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
the webcam_image_ajax.php is created in base64 format and then it upload the gif image from the images folder.
Also when clicked Create GIF button this JavaScript will starting: CLICK.
After that my ajax code have this line webcam_imageload_ajax.php
<?php
include_once 'includes.php';
if(isSet($_POST['webcam']))
{
$newdata=$Wall->Get_Upload_Image($uid,0);
echo "<img src='uploads/".$newdata['image_path']."' class='webcam_preview gifshot-image-preview-section' id='".$newdata['id']."'/>
";
}
?>
the webcam_imageload_ajax.php working with webcam_image_ajax.php.
If webcam_image_ajax.php created image then webcam_imageload_ajax.php echoing image like:
upload/14202558.gif
But now it looks like:
data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAABE...
creat a gif button:
<button type="button" id="create-gif" class="btn btn-large btn-primary create-gif-button camclick" onclick="return takeSnap();">Create GIF</button>
<input type="hidden" id="webcam_count" />
Forget the JavaScript code in the question.
If you want to use this script then use this code from demo.js inside in gifshot plugin.
function create_gif(data){
$.post(
"webcam_image_ajax.php",
{
data: data,
dataType: 'json'
},
function(js_data)
{
var js_d = $.parseJSON(js_data);
$('#gif_preview').attr('src', js_d.path);
if(js_d.id != 'error'){
$("#uploadvalues").val(js_d.id);
$('.webcam_preview, .gifshot-image-preview-section').attr('id', js_d.id);
}
}
);
}
and you can write your own php code for webcam_image_ajax.php.
Simply do like this:
file_put_contents('filename',file_get_contents(str_replace('data:','data://','<your base64 encoded data>')));
This is simply adapting your data:... into the data:// wrapper.
There is no simpler way to do this.
Notice that this is HIGHLY UNSECURE and you should validate the data (using preg_match for example) before usage.

jQuery caching issue ajax?

Done a little work and I think I've found the answer...jQuery's live function.
But it leads to an issue. What I want to do is refresh the content of a div with id of container with new content. The original content had jQuery calls, so when the new content is loaded, I want it to be able to be called by jQuery as well (if that makes sense). Which is where I read jQuery's old .live function worked (by attaching stuff on page load and all times in the future until a true page refresh).
My jQuery is as follows:
$(document).ready(function() {
$('.fancybox').fancybox({
width : '1000px',
height : '1000px',
afterShow : function() {
$( ".fancybox-wrap" ).draggable();
}
});
var sourceSwap = function () {
var newSource = $(this).data('alt-src');
$(this).data('alt-src', $(this).attr('src'));
$(this).attr('src', newSource);
}
$(function () {
$('img.xyz').hover(sourceSwap, sourceSwap);
});
var originalContent = $('.player').html();
var originalContent2 = $('.coords').html();
$('img.xyz').hover(function() {
var player = $(this).data('player');
var coords = $(this).data('coords');
$('.player').html('<strong>'+ player +'</strong>');
$('.coords').html('<strong>'+ coords +'</strong>');
}, function() {
$('.player').html(originalContent);
$('.coords').html(originalContent2);
});
});
var centerX = <?=$_GET['x']?>;
var centerY = <?=$_GET['y']?>;
$(function(){
var hor = 0;
var vert = 0;
$('#left').click(function () {
scroll = $('#container').scrollLeft();
$('#container').animate({'scrollLeft': scroll-300},1000);
centerX = centerX - 5;
hor--;
if(hor <= -3){mapRefresh();}
});
$('#right').click(function () {
scroll = $('#container').scrollLeft();
$('#container').animate({'scrollLeft': scroll+300},1000);
centerX = centerX + 5;
hor++;
if(hor >= 3){mapRefresh();}
});
$('#up').click(function () {
scroll = $('#container').scrollTop();
$('#container').animate({'scrollTop': scroll-300},1000);
centerY = centerY - 5;
vert++;
console.log(vert, " vert");
if(vert >= 3){mapRefresh();}
});
$('#down').click(function () {
scroll = $('#container').scrollTop();
$('#container').animate({'scrollTop': scroll+300},1000);
centerY = centerY + 5;
vert--;
if(vert <= -3){mapRefresh();}
});
<? $totalHeight = 60 * 42;
$totalWidth = 60 * 42;?>
$('#container').scrollTop((<?=$totalHeight?>-$('#container').height())/2).scrollLeft((<?=$totalWidth?>-$('#container').width())/2);
});
function mapRefresh() {
$.ajax({
type : "POST",
cache : false,
url : "map2.php?map=refresh",
data : {'X': centerX, 'Y': centerY},
success : function(data) {
$("#container").html(data);
}
});
}
The stuff like $('#down').click(function () { I believe is simple to replace to $('#down').on( "click", function() {, but what of var sourceSwap = function () { or $(function () {? Those aren't "clicks" or "scrolls" or anything...those are just there, and need to be called on load, and then what of $('.fancybox').fancybox({?
I am new to javascript/jQuery and confused. I've figured the above out, but the only thing I can think of doing is including all the jQuery in the div id container, and replacing it with an exact copy of itself so that it re-runs, but then that seems to cache both the original running and the second running of the jQuery, so that it will run two ajax requests simultaneously, and then three at once, and then four at once, etc. the more times up/down/left/right are clicked.

Bootstrap Popover Displaying the Same Contents

Has anyone worked with the bootstrap popover? I am facing a little difficulty implementing it.
I am creating movie thumbnails dynamically, and on mouseenter event, I am using the popover to display the details of the image. The problem is, the same details are displayed for all the images.
Here is some part of my code:
<script>
$(function () {
$(".get-movies").click(getEventHandler);
});
function getEventHandler() {
var name = $(".get-movie-name").val();
$.ajax({
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=my_key&q=" + name + "&page_limit=5",
dataType: "jsonp",
success: function (response) {
$(".display-movie").empty();
var ul = $(".display-movie");
for (var i = 0; i < response.movies.length; i++) {
var img = $("<img>").attr("src", response.movies[i].posters.original)
.attr("id", i)
.attr("data-placement", "right")
.attr("class", "img-popover")
.on("mouseover", response, getPopOver)
.on("mouseout", hidePopOver)
.css({
width: 200,
height: 200,
margin: 20
});
var div = $("<div>")
.append(img)
$("<li>")
.append(div)
.appendTo(ul);
}
}
});
}
function getPopOver(info) {
console.log(info);
var image = '<img src = " ' +info.data.movies[info.target.id].posters.thumbnail+ ' " />';
$(".img-popover").popover({
title: info.data.movies[info.target.id].title,
content: image,
trigger: "hover",
html: true
})
}
function hidePopOver() {
console.log("Leaving here");
$(".img-popover").popover("hide");
}
</script>
I think your:
var name = $(".get-movie-name").val();
will return the first item in the collection of items that match that class.
you might try:
var name = $('#' +this.id + ".get-movie-name").val();
but without seeing some of the html, I cannot be exact here.

How do can I get links to act independent of each other?

My code currently allows any link clicked under citations to open a new page. I'm trying to exclude the "More..." links from performing this function since these are used to add more links to the current page. Is there a way to do this?
Here's the jsfiddle
Here's my javascript
$(document).ready(function ($) {
var url = 'https://www.sciencebase.gov/catalog/item/504216b6e4b04b508bfd333b?
format=jsonp&fields=relationships,title,body,contacts';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
var citeCount = 0;
var piCount = 0;
$('#project').append('<li><b>' + json.title + ' - </b>' + json.body + '</li>');
$('#project a').on('click', function (e) {
e.preventDefault();
if (citeCount == 1) {
return;
}
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
// Loop function for each section (10 citations per section)
var loopSection = function (start, stop) {
// Http setup for all links
var linkBase = "http://www.sciencebase.gov/catalog/item/";
// Link for citation information
var link = "";
for (var j = start; j < stop; j++) {
// Create a link using the realtedItemId
link = linkBase + json[j].relatedItemId;
// Title links
var $anchor = $("<a>", {
href: link,
id: "id" + j,
text: json[j].title
});
// .parent() will get the <li> that was just created and append to
//the first citation element
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
}
var itemCount = json.length;
var numSections = Math.floor((itemCount / 10));
var moreLinks = $('More...');
var loopCount = 1;
loopSection(0, 10);
$('#citations').append(moreLinks);
$(moreLinks).on('click', function (e) {
e.preventDefault();
if (numSections > 1) {
loopSection((loopCount * 10), ((loopCount + 1) * 10));
$('#citations').append(moreLinks);
numSections -= 1;
loopCount++;
} else if (numSections <= 1) {
$("#nextLink").closest('a').remove();
loopSection((loopCount * 10), json.length);
}
});
},
error: function (e) {
console.log(e.message);
}
}); // END Second .ajax call
$('#project').on('click', function (e) {
e.preventDefault();
if (piCount == 1) {
return;
}
for (var i = 1; i < json.contacts.length; i++) {
$('#piHeading').append('<ul>' + "Name: " + json.contacts[i].name + ', ' + "Email: " + json.contacts[i].email + ', ' + "Phone: " + json.contacts[i].phone + '</ul>');
}
piCount++;
});
citeCount++;
}); // END Project link click event
$('#citations').on('click', function (e) {
e.preventDefault();
window.open('CitationsInfo.html', '_self');
});
},
error: function (e) {
console.log(e.message);
}
}); // END First .ajax call
}); // END Doc.ready
and Here's my html,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="MainPage4.js"></script>
<script src="Citations.js"></script>
</head>
<body>
<h2>Project</h2>
<div class='wrapper'>
<ul id='project'></ul>
</div>
<h3>Citations</h3>
<div class='wrapper'>
<ul id='citations'></ul>
</div>
<h3>Principal Investigators</h3>
<div class='wrapper'>
<ul id='piHeading'></ul>
</div>
</body>
</html>
Thanks for the help
If you change the part of your code that is handling the global click event for the #citations container to include logic to filter out clicks where the target is the #nextLink, it should do what you want.
$('#citations').on('click', function (e) {
e.preventDefault();
if (!$(e.target).is($('#nextLink'))) {
window.open('CitationsInfo.html', '_self');
}
});
Removing the above section entirely also allow the "More..." link to work correctly, while still maintaining functionality on the individual links. The citations click event is masking the other behaviors.
jsfiddle

Categories

Resources