Image as a post variable - javascript

I am working on a site where there is a feature for users to be able to sign directly on the webpage using a canvas free form pen tool. When users click the 'apply signature' button the signature that the user drew is converted into an image and saved on the page as an <img src=""> (as you can see in the code below). Up until this point everything works great.
The problem is, When the user submits the form, I am trying to get the newly created canvas image to submit with it as a post variable and render on the process.php page as the signature that was signed. It appears that image (toDataURL()) gets passed as a post variable, but for some reason it does not render on the process.php page. It appears like the image source is not found.
I am new to javascript and I have been trying to fix this problem for days now, I would appreciate any help with fixing this. Many thanks in advance!
Markup
<div class="signature-field">
Sign:
<span class="sketch-container">
<canvas id="simple_sketch" width="350" height="100"></canvas>
</span>
Date: <input name="signature-date" type="text"><br/>
<div class="signature-buttons">
<span class="save-signature">Apply Signature | </span>
<span class="reset-canvas">| Reset Signature</span><br/>
</div>
</div>
<form method="post" action="process.php">
<input type="text" name="fname">
<input id="signature" name="signature" type="hidden">
<input type="submit">
</form>
JavaScript
$(function () {
var sktch = $('#simple_sketch').sketch();
var cleanCanvas = $('#simple_sketch')[0];
$('.save-signature').click(function () {
/* replace canvas with image */
var canvas = document.getElementById("simple_sketch");
var img = canvas.toDataURL("image/png");
$('#simple_sketch').replaceWith('<img src="' + img + '"/>');
$('.signature-buttons').replaceWith('');
document.getElementById("signature").value = $('.sketch-container').html();
});
});

I'm not quite sure what you're doing here, but if you want to post the image data through the hidden signature field, simply do this:
document.getElementById("signature").value = document.getElementById("simple_sketch").toDataURL("image/png");
As right now, it looks like you're posting the image data including <img> tags ("<img src="<DataUrl>"/>")

How about your server-side code, is the img param output empty? Are you sure the img data is being sent through the request? Try some packet sniffing tool like Fiddler or Wireshark and analyze the contents of the request (You can also take a quick look with Firebug).
Perhaps you could try some other approach to convert the img data:
https://developer.mozilla.org/en-US/docs/HTML/Canvas/Pixel_manipulation_with_canvas

Related

How to change a HTML-element to the selection of a File-Dialog?

I am currently working on a python program that uses a html/css interface which is connected through eel. It requires the user to load a file to analyze. In order to show the user on the User interface which file was selected, I want to show the name of the file (or the path) after the selection process is done.
Since I am new to this, I found a simple filedialog on the internet (probably somewhere here on Stackoverflow) that uses JQuery to select the path to a file. The selection works fine and my program can work with that information if the file that is being selected is located in the same folder as the html file, as this circumvents fakepath errors and I do not know a way around it.
I want to display the selected path underneath the button once it has been selected. However, in the current configuration it displays [object object] right after clicking the "Browserino" button and not the selected path or (ideally) the selected filename.
The HTML document contains:
<div class="col">
<button id="button" class="btn btn-primary" onclick="clicked();">Browserino</button>
<input id="file-input" type="file" name="name" style="display: none;" />
<small id="pathway" class="form-text text-muted">invisible</small>
</div>
And the main.js has this function to work with:
function clicked(){
var path = String($('#file-input').trigger('click'));
document.getElementById('pathway').innerHTML = path;
document.getElementById('pathway').style.visibility = 'visible';
}
I have also tried the follwing in the main.js, but it does not do the trick for me:
function clicked(){
String($('#file-input').trigger('click'));
var file_input = document.getElementById('file-input').value;
var filepath = file_input.replace(/^.*[\\\/]/, '');
document.getElementById('pathway').innerHTML = filepath;
}
Thanks for all the comments before, I hope this edit helps clarify the problem. Any help is appreciated. Thx.

Clear form after submit image in Meteor

I’m using CFS for files upload in my Meteor App, almost everything works fine, except because when I try to upload another image, I see my previous sended image in the form, so I need to clear that form after submit the image. I've tried with .reset but it doesn't work. This is my code right now. Thanks for the help.
NewImage.html
<template name="newImage">
<div align="center">
<form align="center">
<div>
<div>
<span class="btn btn-success btn-file">
<input type="file" accept=".gif,.jpg,.png" class="myFileInputimagepub" id="image"/>
</span>
</div>
<div>
<img src="{{currentUser.profile.image}}" alt="Image" width="60px" height="60px" class="img-circle avatar-upload" value=''/>
</div>
</div>
</form>
</div>
</template>
NewImage.js
import './newImage.html';
Template.NewImage.events({
'change .myFileInputimagepub':function(evt,tmpl){
FS.Utility.eachFile(event,function(file){
fileImagespub.insert(file,function(err,fileObj){
if(!err){
var userId = Meteor.userId();
var imageurl = {
'profile.image':'/cfs/files/fileimages/' + fileObj._id
};
setTimeout(function(){
Meteor.users.update(userId,{$set:imageurl});
},2000);
}
})
})
},
'submit form':function(event,template){
event.preventDefault();
template.find("form").reset();
}
});
If the image in question is the one with class .img-circle, the issue is that its src attribute is being dynamically provided. Currently it is currentUser.profile.image. This won't clear just by resetting the form and manually clearing the image's src value would be fighting the framework.
Option 1 (Not Ideal):
If you don't want to keep the image, unset the database change made after the file upload by running something like this:
Meteor.users.update(userId, { $set: { 'profile.image': null }});
This is not ideal as it enables you to continue modifying the database with an image which may not be needed long-term.
Additionally, I'm assuming you're currently using the autopublish/insecure packages. You'll want to remove these before going public with your app as they allow any user to change the database without restriction.
Option 2:
You could save the returned value from your 'change .myFileInputimagepub' event as a ReactiveVar, then only actually run Meteor.users.update (preferably on the server using a Method) when your user submits the form. At that point you could clear the reactive variable.
Using a ReactiveVar will allow you to provide the saved URL to the src attribute via a helper, and then change the ReactiveVar's value when you wish to clear the form.
There's a simple example of manipulating ReactiveVars here: https://gist.github.com/ahoereth/a75d2d6528b1844ad503

php, css, javascript: click on image -> change the image -> call function

I'd like to have 4 images. After click on the image, it will change to different image and call function.
I already have it and it works, but only separately.
Code for changing image. (I put code only for one image):
<form method="post" action="index.php" name="loginform">
<script>
function prvni(img)
{
img.src = "img/green/green_0.jpg";
document.getElementById("image2").src = "img/red/red_0.jpg";
document.getElementById("image3").src = "img/red/red_0.jpg";
}
</script>
<img src="img/red/red_0.jpg" id="image1" onclick=prvni(this) />
</form>
Code for calling function via button (type=submit):
<form method="post" action="index.php" name="loginform">
<input id="user_drink" class="login_input" type="text" name="user_drink" ?> required /><br>
<input type="submit" name="pridat" value="přidat" id="button"/><br>
</form>
and code from different file:
elseif (isset($_POST["pridat"])) {
$this->myfunction();
When I try to change type submit to image, it doesn't work.
Maybe my codes above are not a good way.
Could you help me how to do it (click on image -> change the image -> call function)
Thank you
The only way you can call a php function from javascript is to use Ajax to send a post or get request after changing the image.
See this CodePen for the client side.
And in your php file:
// read the data
$mydata = $_POST['data'];
// perform actions
// return if needed
header('Content-Type: application/json');
echo json_encode(array('returnData' => 'myOtherData'));
Thank you tima
now I'm able to change the image.
Unfortunately I don't know how to call function with your code from another file.
Which part from your php code call the function?
Is there something which fulfill IF condition from different php file below?
if (isset($_POST['data'])) {
$this->myfunction();
Basically I need use image as button, but I want to change image after click on. There will be 4 images for 4 options. When I click one of them image will change and via function write value to mySQL. If I click on another one image will change (First clicked image will change back) and to mySQL will write value for this actual image. myfunction() from my previous post do mySQL and it is working, so i don't need help with it. I mentioned it for better understanding of my problem)
Thank you so much, I am really new (two weeks) with php, JS etc.
Lukas

{"errors":["Invalid image URL"]} with aviary integration

I am doing image editing integration with Aviary.
Below is the html code
<body>
<a href="#" onclick="return launchEditor('editableimage1','http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg');">
<img id="editableimage1" src="http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg"/></a>
<br>
<form id="myform" action="" method="post">
<input id="hf" type="hidden" name="url">
<input type="submit" value="Save" />
</form>
<script type="text/javascript" src="http://feather.aviary.com/js/feather.js"></script>
<!-- Instantiate the widget -->
<script type="text/javascript">
var featherEditor = new Aviary.Feather({
apiKey: '1234567',
apiVersion: 3,
theme: 'light',
tools: ['draw','text'],
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
console.log('newURL '+newURL);
document.getElementById("hf").value=newURL;
featherEditor.close();
//document.forms["myform"].submit();
}
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
</body>
On opening the above html:
Image will be rendered.
On click of the image, image editing tool will open with the image in it.
But if I replace the url with any other image url say http://ipaddress:8080/ImageCheck/imgjsp.jsp which actually renders image in the browser.
Image will be rendered.
On click of the image, image editing tool opens and close immediately with the error {"errors":["Invalid image URL"]} . Tool is unable to get image into its server for editing from my UrL.
What is the difference between "http://ipaddress:8080/ImageCheck/imgjsp.jsp" and "http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg" for tool to behave differently. Any help appreciated
We are getting the same error too, I've did some searching and found this:
https://creativesdk.zendesk.com/hc/en-us/articles/202903359-Migrating-from-the-Aviary-SDK-to-the-Adobe-Creative-SDK-Beta
It looks like Aviary has updated their API
is http://ipaddress:8080/ImageCheck/imgjsp.jsp points to local ip?
according to https://creativesdk.adobe.com/docs/web/#/articles/gettingstarted/index.html, "requires that the image at the location be publicly available as our server must download it.".
On the other hand, we were able to pass base64 encoded image as a value for url parameter. This way, no need to have actual image to be stored first.
(This approach is not working for us when using hi-res version of Aviary image tool).

How to use form submit to load img tag using post?

I have an interactive plotting form like below:
<form method="post">
<img src="plot.cgi" alt="[plot]">
<input type="text" name="plot_settings" value="Type plot settings here.">
<input type="submit" name="submit" value="plot it">
</form>
(Simplified to the bare minimum above to show the point.)
The image is generated by plot.cgi, which sends the browser the new plot. At present, the user clicks the "plot it" button and the whole page reloads, but I'd like just the image to reload. Obviously, I could script each input into a GET request address and replace the img src with that, but post is more desirable, and it seems there should be a more elegant way to make use of the form's submit mechanism.
Is there a way to load the img using POST instead of setting a GET string to it's src?
(jQuery is okay.)
jQuery('form[method="post"]').submit( function( evt ) {
var url = jQuery(this).target();
var data = jQuery(this).serialize();
jQuery.post( url, data, function(data) {
jQuery(this).find('img').src( data.plotURL ); // use server-generated URL for plot img
});
evt.preventDefault();
}

Categories