I have rendered an image via html2canvas and jquery:
<script>
function capture() {
console.log("function is running");
jQuery('#square').html2canvas({
onrendered: function(canvas) {
var url;
url = canvas.toDataURL("image/png");
//Set hidden field's value to image data (base-64 string)
jQuery('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
//var myImage = canvas.toDataURL("image/png");
window.open(url);
jQuery("#myForm").submit();
console.log(jQuery('#img_val').val());
}
});
}
</script>
The code works all fine, and I see the image via the window.opne.
The issue I have is when I submit my form holding the image value is NOT passed. I know it's set because I see that via console.
My form:
<input type="submit" value="Take Screenshot Of Div" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="/save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>
My Save.php
<?php
//save.php code
//Show the image
var_dump($_POST['img_val']);
echo 'Billede:<br />';
echo '<img src="'.$_POST['img_val'].'" />';
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Save the image
file_put_contents('img' . rand(0,10000) . '.png', $unencodedData);
?>
Why is the value of the renderend image not passed via my form - when I know I set it via jQuery ?
Related
I have two functions one is PHP second is JQuery. I want them to activate on same button click. But I want fisrt to activate PHP function and then JQuery. How can I do this. Here is my code. The problem is this line in JQuery function
var imagename = "<?php echo $nameoffile ?>";
When I replace that with hardcoded variable everything work fine. How can I control order of execution ?
HTML :
<form id ="submit_leave_email" enctype="multipart/form-data" method="POST" >
<div class="form1">
<div class="radio-line" id="radio-manager" style="font-size:12px">
<input type="radio" id="rad-400" name="radio-manager" value="No"/> Registered
<input type="radio" id="rad-400" name="radio-manager" value="No"/> Unregistered
</div> <br>
<h4 class="manager" style="font-size:12px">ID of car is :</h4><br><br>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" class="input_1" />
<input id="fileupload" name="uploadedfile" type="file" class="input_1" /><br/>
<input id="brand" type="text" value="Name of car :" class="input_1" name="brand" /><br></div> <br>
<div id = "image" style="width:100px; height:100px"></div></div>
<input id="submit" type="submit" name="submit" value="submit">
</form>
PHP :
<?php
if(isset($_POST['submit'])){
$target_path = "images/";
$nameoffile = basename( $_FILES['uploadedfile']['name']);
$target_path = $target_path . $nameoffile;
echo $nameoffile;
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "There was an error uploading the file, please try again!";
}
}
?>
JQuery :
<script type="text/javascript">
$( "#submit_leave_email" ).submit(function( event ) {
var brand = $('#brand').val();
var id = localStorage.getItem("id");
if($('#rad-400').is(':checked')){
var ide = 'reg';
} else {
var ide = 'unreg';
}
var imagename = "<?php echo $nameoffile ?>";
$.ajax({
type: "POST",
url: "updateCarSql.php",
data: "ide=" + ide + "&id="+ id + "&brand="+
brand+"&imagename="+imagename,
success: function(){
$("#submit_leave_email").fadeOut();
$("#update_success1").fadeIn();
}
});
});
</script>
PHP code runs at the server, jQuery runs at the client so the strict answer to your question is ISSET is executed before the jQuery; however that doesn't really help you.
It looks like you are trying to use PHP to get the file name for your jQuery code before submitting the form. This is a bit of a catch 22 as PHP code won't be run until after you submit the form.
If you want to get the chosen file name you'll need to use javascript. Look at this question - Use jQuery to get the file input's selected filename without the path
Also look at preventDefault as I suspect you don't want to do an ajax call and submit your form.
I have a page where one can upload an image and crop it (to do so i've used this plugin), the result of this crop is then saved in a server.
After looking at the documentation i tried this:
JQUERY
var zis = //some div where i uploaded the image;
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
zis.find('#img_val').val(imageData);
zis.find('.salvaImmagine').click();
});
PHP
public function immagine_profilo(){
if (isset($_POST['crop'])){
var_dump($_POST['img_val']);
// Get the base-64 string from data
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// Decode the string
$unencodedData = base64_decode($filteredData);
// image new name
$newfilename = 'images/immProf' . $_SESSION['auth'] . '.png';
file_put_contents($newfilename, $unencodedData);
// saves the path into a database
$query = "UPDATE users SET pic = '{$newfilename}'
WHERE id = {$_SESSION['auth']}";
$result = mysqli_query($_SESSION['connessione'], $query);
return // function to retrive the image;
}
}
So far so good, the images is saved in the server, its path is saves aswell, only one problem remains: the page needs to be reloaded in order to see the image change, ok we can do better: update the image without a page reload.
So i searched the web to find out about ajax, after some time i've come up with this:
JQUERY
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
zis.find('#img_val').val(imageData);
lightbox(false);
zis.find('.salvaImmagine').click();
});
$('.salvaImmagine').on('click', function(event) {
event.preventDefault();
var imageData = $('.cop').cropit('export');
$.ajax({
url: 'lib/ottieniCose.php',
type: 'POST',
dataType: 'html',
data: {
crop: 'Salva',
crop_cop: 'Salva',
img_val: imageData
},
})
.done(function(response) {
console.log("success");
$(".copertina").css('background-image', 'url(' + response + ')');
})
.fail(function() {
console.log("error");
})
});
PHP (lib/ottieniCose.php)
//rquire bla bla bla
if (isset($_POST['crop']) || isset($_POST['crop_cop'])) {
var_dump("test");
//calls the function to save the image
$login->immagine_profilo();
}
Now, i get absolutely no result, the images isn't saved, the path isn't saved, the php page doesn't seem to be called at all (althoug there are no 404 errors) but the image is being cropped, i know that by looking into the code.
I also tried changing the POST method to GET method in ajax, but i get error 414, any help?
the HTML
<div id="lightbox">
<div class="image-editor">
<div class="scegliImm">
<p>Scegli un'imagine</p>
</div>
<input type="file" class="cropit-image-input">
<div class="cropit-image-preview-container">
<div class="cropit-image-preview" style="background-image: url(<?php print $login->get_profile_pic() ?>)"></div>
</div>
<div class="image-size-label">
<p>Nessuna immagine selzionata,<br> seleziona un'immagine.<br>P.S. Puoi trascinare l'immagine<br> nuova sopra quella vecchia</p>
<div class="esci">
<p>Esci</p>
</div>
</div>
<div class="neh">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
<input type="hidden" name="img_val" id="img_val" value="">
<input type="submit" name="crop" value="Salva" class="salvaImmagine">
</div>
</form>
<div id="salvaImma">
<input type="range" class="cropit-image-zoom-input">
<button class="export">Salva</button>
</div>
</div>
</div>
</div>
Try to give absolute path to that ajax call or if your lib folder at the root of your website then use backslash before the lib
so your url will be :- /lib/ottieniCose.php
It may help you.
I have a modal containing a form and an iframe.
The form has a file field and post to the iframe.
The php controller return the uniqid (basically the name) of the uploaded file.
The upload works well and my iframe contains the uniqid.
I would like to display this uniqid on my main page.
My issue is that I don't know how to wait the end of the upload to show the uniqid.
The form and iframe :
<form id="uploadForm" enctype="multipart/form-data" action="{{ path('lesson_upload') }}" target="uploadFrame" method="post">
<label for="uploadFile">Document :</label>
<input id="uploadFile" name="uploadFile" type="file" />
<br /><br />
<input class="btn btn-primary" id="uploadSubmit" type="submit" value="Upload" />
</form>
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden id="uploadFrame" name="uploadFrame"></iframe>
</div>
The JavaScript to fill the modal with the form :
$(document).on('click', '#computer-upload', function ()
{
var url = Routing.generate('lesson_upload_computer');
$.get(url, function (data)
{
$('#modal-various .modal-body').html(data);
return false;
});
return false;
});
The iframe at the end of an upload :
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden="" id="uploadFrame" name="uploadFrame">
#document
<html>
<body>
<body>533ebac647b7e</body>
</body>
</html>
</iframe>
</div>
Does anyone have an idea ?
Thanks !
If you don't use an AJAX upload, after a little research, you cannot add an event that detects when the upload has finished.
You now have 2 options:
Fetch the id from the iframe every ~100ms and if it is not empty or null, the id will be in:
document.checkForId = function() {
id = $('#uploadFrame').contents().find('#idInIframeDivOrOtherContainer');
if (id) {
window.clearInterval(intervalId);
}
};
$(document).ready(function() {
intervalId = window.setInterval('document.checkForId', 100);
});
When posting data, return javascript that sets the id in the main page (if you have jquery in the iframe):
<script>
$(document).ready(function() {
$('#divInParentWindow', parent.document).text('<?php echo $id; ?>');
});
</script>
If your iFrame has its source on the same server/domain level as your main page. You could simply define a function at your main page
function iframeHasLoaded() {
var body = document.getElementById('uploadFrame').contentWindow.document.body.innerHTML;
}
And, from your iFrame
window.onload=function() { parent.iframeHasLoaded() };
This should work.
I've the code which takes the screen shot of the specified div tab. But I'm encountering the problem to display it as .png file from base64 format
Here is my code.
It has two separate files
1) Download.php
<script type="text/javascript"src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<!-- -->
<div id="target">
<img src="images/1.jpg" alt="Smiley face" width="100" height="100">
</div>
<script type="text/javascript">
function capture() {
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
document.getElementById("myForm").submit();
}
});
}
</script>
<input type="submit" value="Take Screenshot Of Div" onclick="return capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>
2)Save.php
<?php
//Show the image
$data = $_POST['img_val'];
//Get the base-64 string from data
$uri = substr($data, strpos($data, ",") + 1);
//Decode the string
$unencodedData = base64_decode($uri);
$im = str_replace($data, '+', 'img.png');
//Save the image
$v = file_put_contents($data, $im);
$result = '<img src="' . $im . '" />';
print_r($result);
?>
I need the image to be displayed as localhost/xyz/screenshot/img.png which I'm unable to do.Please see the code help me to figure out that problem.
Thanks in advance.
I cant see any element in html with id attribute of target in your code but you are using it
$('#target').html2canvas({
Similar question [here][1]
I have found some thing usefull
var html2obj = html2canvas($('body'));
var queue = html2obj.parse();
var canvas = html2obj.render(queue);
var img = canvas.toDataURL();
window.open(img);
[1]: http://stac
koverflow.com/questions/10457608/create-screenshot-of-webpage-using-html2canvas-unable-to-initialize-properly
I have a form with number of input type images. I need to replace the webpage location to url of the image when a user clicks any image.
form is like,
<form action='free.php' id='freeForm' method='post' autocomplete="off">
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" />
<?
}
?>
</form>
$img and $url values from database.
My jquery is like,
$("#freeForm").submit(function()
{
var Form = { };
Form['inputFree'] = $("#inputFree").val();
Form['freeTOS'] = '1';
$('.anchor-url').click(function(e){
e.preventDefault();
alert($(this).attr('href'));
});
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
Now I am getting 'http://au.yahoo.com' when i click each image. But I want to replace 'http://au.yahoo.com' with URL of each image. How can I pass the PHP variable $url to this form?
Any idea?
Thanks!
This should work, if I understood what you were asking for correctly and though I haven't tried it. Basically you bind the click event to each image, and on click it replaces the window location with the value in the src attribute of the input element being clicked on.
$('input[type=image]').click(function(e){
e.preventDefault();
window.location.replace($(this).attr('src'));
});
EDIT
First you should add a class name to your anchor elements:
<form action='free.php' id='freeForm' method='post' autocomplete="off">
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" />
<?
}
?>
</form>
Your JS:
$('.anchor-url').click(function(e){
e.preventDefault();
window.location.replace($(this).attr('href'));
});
Notice how I added a class to the anchor links. This can be named almost anything. This gives you the ability to select for those elements with that classname only with jQuery using the $('.any-classname') selector.