html2canvas capturing div image - javascript

im working on my wordpress site in which i want a div to be converted to image.. im using html2canvas javascript and it works perfect. when i capture a post it saves it to the server has "Captured.jpg". all good till here.. but when i click capture again on a different post it replaces the previous image "captured.jpg". i want all the images of the posts that i capture to be saved on server with post names may be? is it possible?
Header
<script type="text/javascript">
function capture() {
$("#quotesingle").html2canvas({
canvas: hidden_screenshot,
onrendered: function() {
var img = $("#hidden_screenshot")[0].toDataURL();
img= img.replace('data:image/png;base64','');
$form = '<form name="frmact" action="result.php" method="post" ><input type="hidden" name="img" value="' + img + '" /></form>';
$('body').append($form);
frmact.submit();
$('body').remove($form);
}
});
}
</script>
Results.php
<?php
$canvasImg = $_POST['img'];
$data = base64_decode($canvasImg);
$File = "captured.jpg";
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
fclose($Handle);
?>
captured.jpg is saved.
single.php
//POSTLOOP
<input type=button value="Screenshot" onclick="javascript:capture();" /><br /><br /></div>
<canvas id="hidden_screenshot" style="display:none;" >
is there any way if i trigger the capture for a post to save in a different name or post name or post id.. so it saves it to the server without replacing the old?
thanks

Result.php
Simple change the file name as below:
$File = "screens/" . time() . ".jpg";

Related

Ajax Php Image Upload and Save

I want to upload an image and save it in the uploads folder without refreshing the page. Furthermore, I also want to display the uploaded image on the screen in a div. However, when I run the code, when I try to upload an image, the text continues to say "Image Uploading..." and never finishes to actually upload. Therefore, the image never gets displayed on the page. Additionally, I am having trouble saving my image in the uploads folder, so can someone point me in the right direction? Thank you!
UPDATE: The Ajax POST gets an error each time I try to to upload an image. In fact, the POST request might not even reach my upload.php file. I trie d to alert myself when the request actually reaches upload.php but nothing ever prints out. What may be the potential causes of this?
UPDATE #2: I have included a picture of my file layout. I have the HTML and Javascript in privatecreate.blade.php and the Javascript in upload.php. I want to save the images in uploads folder.
Update #3: I printed out the ajax error and it is "No Input File Specified"
Please bear with my everyone. This is my absolute first time working with php and sql and I am trying my hardest to learn.
HTML:
<div class="container" style="width:700px;">
<br />
<label>Select Image</label>
<input type="file" name="file" id="file" />
<br />
<span id="uploaded_image"></span>
</div>
Javascript:
$(document).ready(function(){
$(document).on('change', '#file', function(){
var name = document.getElementById("file").files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
else{
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
,error: function(ts)
{
alert("error:" + ts.responseText);
}
});
}
}
});
});
PHP (upload.php):
<?php
//upload.php
$message = "Running Upload.php";
echo "<script type='text/javascript'>alert('$message');</script>";
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'uploads/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>
<?php
//Change your location path
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'upload/' . $name; // change here & enjoy
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>

looping file upload form with PHP

im currently using jquery booklet Moleskine Notebook with jQuery Booklet to make a logbook with some images to be uploaded for every page.
what im doing is im looping the div of every page in php as im calling data from DB, but when i tried to use file upload form as follows , it only works on first page on. the upload button appeared on every other page but it does nothing, not even call the upload window.
every page has its own log_id $row['log_id'].
so any solution is much appreciated.
if (mysqli_multi_query($conn, $sql)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_array($result)){
echo '<div>';
echo ' <form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="php/multiple_upload.php">';
echo ' <input type="hidden" name="form_submit" value="1"/>';
echo ' <input type="file" class="hidden" name="images[]" id="upload-images" multiple >';
echo ' <input name="log_id" type="hidden" value="'.$row['log_id'].'">' ;
echo ' </form>';
echo '</div>' ;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($conn));
}
and the here is the script for calling form
$(document).ready(function(){
$('#upload-images').on('change',function(){
$('#upload_form').ajaxForm({
beforeSubmit:function(e){
$('.progress').show();
},
success:function(e){
$('.progress').hide();
location.reload(true);
},
error:function(e){
}
}).submit();
});
});
If you're using id $('#upload_form').ajaxForm({***});. This will only find and target the first #upload_form
And if you're using class like $('.upload_form').ajaxForm({***});. This will find and target all the form class .upload_form
You need to define which form you're looking for. In this case, You just need to find the closest/parent of .upload-images form. Like below.
Do like this.
$(document).ready(function(){
$('.upload-images').on('change',function(){
$(this).closest('form').ajaxForm({ // target the parent form
beforeSubmit:function(e){
$('.progress').show();
},
success:function(e){
$('.progress').hide();
location.reload(true);
},
error:function(e){
}
}).submit();
});
});

Parse a redirect page with php Simple HTML DOM

I am dynamically generating a url to be parsed with PHP Simple HTML DOM but that page directs to another dynamically greated URL using Javascript, below is the script that redirects it
<script>window.addEventListener('load', function() { window.location.replace('http://thatsthem.com/search/417-272-0471/7312f62d') });</script>
So I need a way for the PHP to follow the redirect through to http://thatsthem.com/search/417-272-0471/7312f62d and then parse that page. But all it does is just load that javascript and then executes it and opens the new page.
Or if I can some how extract the URL from the javascript with regex or something and then have my PHP just parse that url, that would work also. But I can't figure out how to get that url out of the script with php.
I feel like I'm in Inception right now
Thanks in advance!
Here my script is
<body>
<form method="post" id="primarysearchfomr">
<input name="number" type="text" value=""/>
<input type="submit" id="searchbutton"/>
</form>
<h1 id="searchform">Search Form</h1>
<?php
$searchterm= $_POST["number"];
$count = null;
$returnValue = str_replace(array("(",")","-"," "), '', $searchterm, $count);
include_once('simple_html_dom.php');
$target_url = "http://thatsthem.com/searching?ff=true&q0=" . $returnValue;
$html = new simple_html_dom();
$html->load_file($target_url);
foreach($html->find('script',2) as $link)
{
echo $link;
}
So you just want to pull that url out with regex? That should look something like:
$script = "<script>window.addEventListener('load', function() { window.location.replace('http://thatsthem.com/search/417-272-0471/7312f62d') });</script>";
if(preg_match("/'(http.*?)'/", $script, $m)){
$url = $m[1];
die($url);
}

PHP upload with dynamic url by action attribute.

I am trying to upload matlab file using php onto my server. I need to pass this file as the part of php url so that I can take out this from url and pass on this to some code in custom shell script.
Here is the script I am using to change the URL but then the file is not uploading.
HTML Code:
<script type="text/javascript">
window.onload = function(){
var form = document.getElementById("phpForm");
form.onsubmit = function(){
var matlabfile = document.getElementById("fileToUpload");
var filename = matlabfile.value;
var filename2=filename.replace(/^.*\\/, "");
var filename3=filename2.substr(0, filename2.lastIndexOf('.'));
window.location = "upload.php?matlabfile=" + filename3
return false;
};
};
</script>
<form action="" id="phpForm" method="post"
name="phpForm" enctype="multipart/form-data>
<table style=" text-align:center;">
<tr>
<td><b>File 1:</b> <input id=
"fileToUpload" name="fileToUpload"
type="file"></td>
</tr>
<tr>
<td><input name="submit" type=
"submit" value=
"Upload Script"></td>
</tr>
</table>
</form>
PHP Code:
<?php
$targetfolder = "";
$targetfolder = $targetfolder . basename( $_FILES['fileToUpload']['name']) ;
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetfolder)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " is uploaded";
}
else {
echo "Problem uploading file";
}
$var1=$_GET['matlabfile'];
echo "<pre>$var1</pre>";
echo "matlabfile : ".$_GET['matlabfile']."<br>";
$output = shell_exec("./n.sh $var1 2>&1");
echo "<pre>$output</pre>";
?>
Could you please tell me what I am doing wrong.
Looking forward to your replies.
Thanks and Best Regards,
Shivam Dixit
Your 'return false;' is preventing the submission of the form, and then the file isn't uploaded. You're simply moving the user to another address.
Instead of
window.location = "upload.php?matlabfile=" + filename3;
return false;
try to set the form action to the url you want:
form.setAttribute('action', "upload.php?matlabfile=" + filename3);
Then, the user will be sent to the page you want, and the file will be uploaded :)

Why wont javascript get values of php generated html?

im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.

Categories

Resources