how to show last canvas image - php

im trying to find a way to only show las signature created in canvas, but the problem is that senes the img don't save in the DB i cant limit 1; like in mysqli_query or can you??
This is where the signature is created.
<div id="signArea" >
<h2 class="tag-ingo">Put signature below,</h2>
<div class="sig sigWrapper" style="height:auto;">
<div class="typed"></div>
<canvas class="sign-pad" id="sign-pad" width="300" height="100"></canvas>
</div>
</div>
<button id="btnSaveSign">Save Signature</button>
when the signature is created it call this function which saves the signature to a file :
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true,
drawBezierCurves:true, lineTop:90});
});
$("#btnSaveSign").click(function(e) {
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data =canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
save_sign.php
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = md5(date("dmYhisA"));
//Location to where you want to created sign image
$file_name = 'doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
The output loads like this:
<?php
$image_list = glob("doc_signs/*.png");
foreach($image_list as $image){
?>
my problem is that it loads all images saved in the file , is there any whay to ony load last image and reset on load page??? .

Related

the image remains the same after being updated and uploaded with new images

I have uploaded the image and crop it with croppie, the image successfully updates the database and successfully enters the directory.
but the new image overwrites the old image with the same name, it was intentionally done. but the image displayed again by php remains the old image (the image has been overwritten with the new one)
Initially there was no problem but when I didn't open the project for more than 2 week there was a problem like the one above
HTML tag
<div class="col-sm-3">
<h4>Profile Picture</h4>
<hr>
<form action="" id="form" method="post">
<label class="cabinet center-block">
<figure><img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
</div>
JS with CROPPIE
<script type="text/javascript">
// Start upload preview image
$(".gambar").attr("src", "../profile/pictures/img/<?=$profile['profile']?>");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Desculpe, seu navegador não suporta o FileReader API.");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 230,
height: 230,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'jpeg',
size: {width: 270, height: 270}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
//$('#cropImagePop').modal('hide');
$.ajax({
url: "../lib/proses/upload.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img src="' + resp + '" />';
$("#upload-image-i").html(html);
$('#cropImagePop').modal('hide');
swal.fire(
'Berhasil !',
'Profile berhasil diubah',
'success'
)
}
});
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
</script>
Upload Process
<?php
session_start();
require "../koneksi.php";
$username = $_SESSION['username'];
$croped_image = $_POST['image'];
list($type, $croped_image) = explode(';', $croped_image);
list(, $croped_image) = explode(',', $croped_image);
$croped_image = base64_decode($croped_image);
$image_name = $username.'.png';
// insert name to database
$sql = "UPDATE users SET profile = '$image_name' WHERE username = '$username'";
$query = mysqli_query($conn, $sql);
// upload cropped image to server
file_put_contents('../../profile/pictures/img/'.$image_name, $croped_image);
?>
I want the newly uploaded image to appear to replace the old image in
the file that displays the image (ex. index file, etc.)
Have you checked your browser cache? Maybe try adding a random param to image path, like myimage.jpg?c=[randomNumber], this will force the browser to download the image again.
Clear your cache, are you using a PHP framework?

I want to show image in img tag when ajax is call in codeigniter

I want to show an image in img tag. when ajax is called in CodeIgniter.
this is the code which receives the data from the database and displays it in a bootstrap model. but the main problem is that I want to show an image in img tag but it not showing.
$(".Edit-modal").on("shown.bs.modal", function (e) {
var button = $(e.relatedTarget);
var ID = button.parents("tr").attr("data-id");
var modal = $(this);
$.ajax({
url: "'.base_url().'Employees/master_get_employees",
data: {ID:ID},
type: "POST",
success:function(output){
try{
var outputData = JSON.parse(output);
modal.find("#EditImage").attr("'.base_url().'src",outputData.pic);
}
catch(ex){
var split = output.split("::");
if(split[0] === "FAIL"){
Shafiq.notification(split[1],split[2])
}else{
Shafiq.notification("Could Not Load Data, Please Contact System Administrator For Further Assistance","error");
}
}
}
});
});
And This is the Img tag where I want to display image.
<div class="col-md-3">
<div class="form-group">
<label for="EditcontactNoSelector">Employee Picture</label>
<img src="" id="EditImage" alt="Not Found">
</div>
</div>
And this is the function through which data is fetched from the database
public function master_get_employees()
{
if ($this->input->post()) { //If Any Values Posted
if ($this->input->is_ajax_request()) { //If Request Generated From Ajax
$ID = $this->input->post('ID');
if (!isset($ID) || !is_numeric($ID)) {
echo "FAIL::Something went wrong with POST request, Please contact system administrator for further assistance::error";
return;
}
$table = "employees e";
$selectData = "e.id AS ID,e.Phone,e.Mobile,e.CNIC,e.Perm_Address,e.Picture as pic,d.name as Designation,s.title as Shift, e.Name,e.Father_Name AS FatherName,e.Phone AS Contact,e.JoinDate,e.BasicSalary, e.Pres_Address AS Address,e.IsEnabled";
$where = array(
'e.id' => $ID, 'e.IsActive' => 1
);
$result = $this->Common_model->select_fields_where_like_join($table, $selectData,$where, TRUE);
print json_encode($result,JSON_UNESCAPED_SLASHES);
}
}
}
I guess you have base_url() function in javascript to find base url of you site.
If so then you can use
$("#EditImage").attr("src",base_url()+outputData.pic);
If you don't have base_url() function in javascript you can find it here:
how to get the base url in javascript
instead of this
url: "'.base_url().'Employees/master_get_employees",
You can use below,
url: "<?php echo site_url('Employees/master_get_employees'); ?>",
Also at server side if you need only image url then just create image url from $result, store it in variable like $img_path in "master_get_employees" function and then just
echo json_encode(['img_path'=>$img_path]);
And in ajax success just do below
$("#EditImage").attr('src',outputData.img_path);

How to refresh map only on click category?

Can some help me to solve this problem
I have a map on my website and i want to refresh map only on clicking on category my this is my product
<?php
/* $message = "in home";
echo "<script type='text/javascript'>alert('$message');</script>";*/
foreach($categories as $category){
echo '<li><img src="'.base_url('uploads/'.$category->image).'" alt="'.$category->cat_name.'" width="30" height="30"/></br><span>'.$category->cat_name.'</span></li>';
}
?>
</ul>
</div>
</div>
<script>
function changeData(category){
var urlCI = '.base_url('main/home/' .$category->adv_category).';
$.ajax({
type: "POST",
url: urlCI,
data:{'categoryReq':category},
success: function(response) {
if(response!=''){
$('map_marker').html(response);
}else{
return false;
}
}
});
}
</script>
my controller code is if you need other code please ask i will give. I give this just for refrence, thank you
public function home($cat=NULL)
{
//$cat=10;
//echo debug_backtrace()[1]['function'];
if($_POST)
{
print_result($_POST);
}
$sql="SELECT * FROM (`ad_category`) WHERE `status`=1 AND `del_status`=0";
$this->data['categories']=$this->db->query($sql)->result();
if($cat)
{
//$message = $cat;
//echo "<script type='text/javascript'>alert('$message');</script>";
//$this->data['middle_view']='home_again';
$this->data['ads']=$this->advt_m->get_advts($cat);
$this->input->post('map_marker',$this->data);
$this->data['subview']='home';
$this->load->view('__layout_main',$this->data);
}
else
{
/*$message = "Here 2";
echo "<script type='text/javascript'>alert('$message');</script>";
*/
$this->data['subview']='home';
//$this->data['middle_view']='home';
$this->data['ads']=NULL;
$this->load->view('__layout_main',$this->data);
}
var urlCI = '.base_url('main/home/' .$category->adv_category).';
probably should be
var urlCI = '<?php echo base_url("main/home/$category->adv_category"); ?>';
Split the Map div and its javascripts into another view.
Create function with all necessary functionalities for map. Add and load the it through Ajax call.
Ajax success:
success:function(response){
$('div').html(response);
//response will be the function which holds the $this->load->view('map');
}
map.php
<div id="map">
YOUR MAP GOES HERE
</div>
<script>
MAP SCRIPT
</script>
main.php (Your frontend)
<div id="map_here">
</div>
<script>
$.ajax({
type:"POST",
//Send some values
data:{
somevalue:'somedata',
category:"mine"
},
url:"<?php echo base_url();?>mycontroller/mapfunc",
success:function(response){
$('#map_here').html(response);
}
})
</script>
myconroller:
function mapfunc(){
//Using this value you can change the script
$data['category'] = $_POST('category');
$data['location'] = $_POST('somevalue');
//Process the works
$this->load->view('map',$data);
//On Ajax call this page can be loaded
}
Each ajax call it will reload the div.
any doubts just comment it...

I want to upload file my file

I was getting undefined file as an error in my php while uploading a file.
function click_submit_form() {
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data: $('#id_frm_charity_details').serialize(),
success: function (data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data'>
<input id="id_file" name="file" class="input-file" type="file"> <a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
In my php
<?php
$files = $_FILES['file']['name'];
$files_tmp = $_FILES['file']['tmp_name'];
$copy = copy($files_tmp, $files);
//echo $_POST['file'];
move_uploaded_file($files_tmp, "C:\wamp32\www\jb_from_live\src\uploaded_files/" . $files);
?>
If i use the above line then it says undefined index 'file'.But the execution not going after $files=$_FILES['file']['name'];
It says undefined index file.
Send image to this format
$('#form').submit(function() {
var img=$('#image').val();
var forms=($(this).serialize());
$.ajax({
type:"POST",
url: "do.php?do=upload",
data:forms+'&r='+encodeURIComponent(img),
success: function(result){ //your code }
});
Try this in your code like this
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function click_submit_form(){
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
var img=$('#id_file').val();
var forms=($('#id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data:forms+'&r='+encodeURIComponent(img),
// data: $('#id_frm_charity_details').serialize(),
success: function(data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
</script>
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data' >
<input id="id_file" name="file" class="input-file" type="file">
<a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
I recommend you to use FormData instead of serialize(). The advantage of using formData is that you can also upload pdf,xml,JSON files by specifying their content-type.
For eg:
var fData = new FormData();
fData.append("XML", new Blob([ xml ], { type: "text/xml" });
fData.append("JSON", new Blob([ JSON.stringify(json) ], { type: "application/json" }));
fData.append("PDF", file);
Make sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You cannot upload a file via ajax that simply unfortunately, for security reasons js doesn't have access to file data and therefore cannot post it via the form serialize function.
If you want to validate other parts of the form and then submit you could write a function like this
function submit(){
var valid = true;
//TODO: check validation on form, set valid to false if incorrect
if( valid )
document.forms[0].submit();
return false;
}
If you want to use HTML5 have a geez at this answer which utilizes the FormData() function:
How can I upload files asynchronously?
Otherwise if you with to upload a file asynchronously you'll have to look for a jsp or flash fallback plugin.
Here's a really good one:
http://blueimp.github.io/jQuery-File-Upload/

How to mesh codeigniter with ajax

I am trying to implement a ajax plus one button with my site in code igniter. I am very new with Ajax and codeigniter so I'm needing some guidance.
Here is the portion of my controller where I'm starting. Please note, this is inside the method that creates my profile view in which I'm trying to create this.
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->community_model->updateUpVote($voteId);
}else{
$updateRecords = $this->community_model->updateUpVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// This variable will be accessed from the view
$data['airwave'] = $airwave;
$data['profile_id'] = $profile_id;
$this->load->view('includes/templates/main_page_template', $data);
}
Here is the method in the model:
function updateUpVote($voteId){
$sql = "UPDATE airwaves_comments set thumbsup = thumbsup+1 WHERE thumbsup =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
here is my view:
<div id='thumb_holder'>
<div id='thumb_report'>
<a href='mailto:info#cysticlife.org'>
&#149 report
</a>
</div>
<div class= 'thumb_counter'>
+0
</div>
<div id='thumb_thumb'>
<a class='myButtonLink voteMe' id='1_upvote'<span id="1_upvote_result">+</span>></a>
</div>
</div>
here is the script:
<script>
$(document).ready(function(){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "account/profile/voteMe",
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
</script>
additionally here is what it looks like to give a better idea of what's going on, but I want there to be the number of votes after the plus sign:
To summarize: Essentially I was taking a tutorial on a demo tutorial that is similar, but it was not exactly what I am trying to do. This is basically me taking the code from the tutorial and trying to splice it with my code and meet my specific needs and learning ajax at the same time. I feel like I'm close as it's updating the specified column in my table (incorrectly),however can't get it to visibly function.
I'm not exactly sure what your saying your problem is. But This I do see.
When trying to fetch a view for ajax you have to return the view as data
http://ellislab.com/codeigniter/user-guide/general/views.html (bottom of the page)
Like this
$view = $this->load->view('includes/templates/main_page_template', $data, true);
echo $view;
This will send the rendered view to the browser
Put this code in view file
<input type="hidden" name="siteurl" id="siteurl" value="<?php echo site_url(); ?>">
<input type="hidden" name="baseurl" id="baseurl" value="<?php echo base_url(); ?>">
Then get hidden value in your script
var site_path = $("#siteurl").val();
var base_path = $("#baseurl").val();
$.ajax({
type: "post",
url: site_path+"account/profile/voteMe",....

Categories