I have a canvas element to collect users signature, I then have a button with an onclick function to save the signature to the server, this runs an ajax script to POST the data to a php file.
The problem I have is that although the data gets saved, i have to click the button and then do a page refresh for the save event to actually occur.
Please help me to see where I've gone wrong as I don't wan tto have to do a manual refresh.
The code is below.
Canvas HTML element:
<div class="signature-pad--body">
<canvas id="signCanvas"></canvas>
</div>
<div class="signature-pad--footer">
<div class="description">Sign above</div>
<div class="signature-pad--actions">
<div>
<button type="button" class="button clear" data-action="clear">Clear</button>
<button type="button" class="button" data-action="undo">Undo</button>
</div>
<div>
<input type="button" class="button save" onclick="signUploader()" id="signReady" value="Upload above Signature" />
</div>
</div>
</div>
</div>
JS Ajax script:
<script type="text/javascript">
function signUploader() {
// Generate the image data
var pic = canvas.toDataURL('image/png');
pic = "data="+pic;
console.log(pic); //just for seeing that it's working
$.ajax({
url: "includes/signSave.php",
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "text",
data: pic ,
beforeSend : function() {
$("#signCanvas").fadeOut(); }
});
}
</script>
signSave.php
<?php
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$file = '../../uploads/signature' . time() . '.png';
file_put_contents($file, $fileData);
?>
This is my first time playing with ajax, so please help me out, and explain if there are errors in there.
Thanks
I think you should return true from signSave.php and in success, you can reload the page like below.
'success' : function(data) {
window.location.reload();
}
add
location.reload();
to refresh page after your ajax , since you are not returning anything to ajax
Related
I have text area where I need to load image to <img> tag. Then, I want to post content of text area to generate_pdf.php to generate pdf. I have encauntered URI Too Largeerror when I post text area content by $.ajax({}).
Method 1-$.ajax({}) in $().on("click",function(){}) of submit button
<?php
//image from sql
$image =$array_image[0]['file'];
$encode_img ='"data:image/jpeg;base64,'.base64_encode($image).'"';
?>
<!DOCTYPE html>
<html>
<head>
<script src="../../library/jquery/jquery-3.4.1.min.js"></script>
<script>
$( document ).ready(function()
{
let hd = document.createElement('div'); // Create new DIV
hd.style.display = "none"; // Hide new DIV
hd.innerHTML = document.querySelector('#ta').value; // set its innerHTML to textarea's
document.body.prepend(hd); // Add to body
document.querySelector('#test').src = <?php echo $encode_img;?>;
document.querySelector('#ta').value = hd.innerHTML;
content =$('#ta').val();
$('#test').src = <?php echo $encode_img;?>;
//submitted uri too large
//-(<form id="text_editor" name="text_editor" >)
$('#pdf').on("click",function()
{
$.ajax({
type:"POST",
url :"generate_pdf.php",
data:{
'pdf ' :content,
}
,
success:function(data)
{
alert('successfully posted!');
$('#content').html(data);
}
});
})
})
</script>
</head>
<body>
<form id="test_img" name="test_img" >
<textarea id="ta" name="ta">
<img alt="test" id="test">
</textarea>
<input type="submit" value="Submit" name="pdf" id="pdf">
</form>
<div id="content" name="content"></div>
</body>
</html>
Then , I tried using $.post in $().submit(function(event){}). This able to submit without this error.
Method 2-$.post in $().submit(function(event){}) of form
<?php
//image from sql
$image =$array_image[0]['file'];
$encode_img ='"data:image/jpeg;base64,'.base64_encode($image).'"';
?>
<!DOCTYPE html>
<html>
<head>
<script src="../../library/jquery/jquery-3.4.1.min.js"></script>
<script>
$( document ).ready(function()
{
let hd = document.createElement('div'); // Create new DIV
hd.style.display = "none"; // Hide new DIV
hd.innerHTML = document.querySelector('#ta').value; // set its innerHTML to textarea's
document.body.prepend(hd); // Add to body
document.querySelector('#test').src = <?php echo $encode_img;?>;
document.querySelector('#ta').value = hd.innerHTML;
content =$('#ta').val();
$("#test_img").submit(function(event)
{
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, { pdf:content} );
posting.done(function( data )
{
$('#content').html(data);
});
})
})
</script>
</head>
<body>
<form id="test_img" name="test_img" method="POST" action="generate_pdf.php" >
<textarea id="ta" name="ta">
<img alt="test" id="test">
</textarea>
<input type="submit" value="Submit" name="pdf" id="pdf">
</form>
<div id="content" name="content"></div>
</body>
</html>
$.post is a shorthand for $.ajax.But, why method 2 able to submit successfully and first method could not? In method 1, content of data that we posting included in url. But, in second method, not included. Thanks in advance.
Adding preventDefault() method in $('#pdf').on("click",function() {}) had solve error URI Too Large.
The preventDefault() method stops the default action of a selected element from happening by a user. This method does not accept any parameter and works in two ways:
It prevents a link from following the URL so that the browser can't go another page.
It prevents a submit button from submitting a form.
Code:
$('#pdf').on("click",function(e)
{
e.preventDefault();
$.ajax({
type:"POST",
url :"index_debug_uritoolarge_2.php",
data:{
pdf :$('#ta').val(),
},
success: function(data)
{
alert('successfully posted!');
$('#content').html(data);
}
});
})
Reference: post_textarea_content_in_ajax
In my project, I use easyui.
At first, easyui-layout cenDiv has default content.
And then I want to fetch content from server DB througth oat.php with corAnnouncement button.
The default content of cenDiv will be replaced by a panel content from oat.php.
But unfortuately, It works fail.
Here is js code:
function corpAnn()
{
var oaAnn="tp";
$.ajax({
dataType:'html',
type:"POST",
url:"oat.php",
data: {oaAnn:oaAnn},
success:function(data)
{
$('#cenDiv').html(data);
}
});
}
Here is html code:
corAnnouncement<br />
<div id="cenDiv" class="easyui-layout" style="position:static;height:100%" data-options="region:'center',title:''">
......
</div>
Here is oat.php code:
if(isset($_POST['oaAnn']))
{
......
echo '<div class="easyui-panel" closed="true" title="Panel Footer" style="width:700px;height:200px;" data-options="footer:'#ft'">';
echo '<table border=1px cellspacing=0 align="center" size="100%">';
......
}
I have found that
data-options="footer:'#ft'";
is wrong, because echo has single quotation marks.
I have tried:
data-options=footer:'"#ft"' ;
and
data-options=footer:"#ft";
But they works fail. Who can help me?
echo '<div class="easyui-panel" closed="true" title="Panel Footer" style="width:700px;height:200px;" data-options="footer:\'#ft\'">';
I forgot escape character.Maybe I am tired.
Will you please please tell me how to get java variable "data_id" value in PHP Variable "$gal_id" i m not able pass the value of java variable into PHP Variable so please also let me know if you find the solution
JS IN Head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/jquery.colorbox.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//Examples of how to assign the Colorbox event to elements
$(".inline").colorbox({inline:true, width:"70%", height:"500px;"});
});
</script>
HTML
<li><a class='inline' href="#inline_content" data-id="1">ABC</a></li>
<li><a class='inline' href="#inline_content" data-id="2">DEF</a></li>
<li><a class='inline' href="#inline_content" data-id="3">XYZ</a></li>
POPUP Box
<script type="text/javascript">
$('.inline').click(function(){
var data_id = $(this).data('id');
$('#idvalue').html(""+data_id);
});
</script>
<div style='display:none'>
<div id='inline_content'>
<span id="idvalue"></span><!--we'll get here data_id value of clicked list in output -->
<?php
$gal_id = ""; // Will you please please tell me how to get java variable "data_id" value here from above js
$check = mysql_query("select * from img where id = '$gal_id'");
while ($run = mysql_fetch_array($check)){
.
.
.
}?>
</div>
</div>
try this edit... I have integrated ajax with your code
<script type="text/javascript">
$('.inline').click(function(){
var data_id = $(this).data('id');
$('#idvalue').html(""+data_id);
$.ajax({
type: "GET",
url: "ajax.php?gal_id="+data_id,
success: function(data) {
$('#images').html(data);
}
});
});
</script>
<div style='display:none'>
<div id='inline_content'>
<span id="idvalue"></span>
<span id="images"></span>
</div>
</div>
create a new file ajax.php
and put this code there...
<?php
//whatever content you will echo here will be send to the main page and put to #images span tag...
//put your connection string here.. to connect the database
$gal_id = $_GET['gal_id'];
$check = mysql_query("select * from img where id = '$gal_id'");
while ($run = mysql_fetch_array($check)){
.
.
.
}?>
If I understood your question, you can't do it this way.
You can check this other question that can surely help you:
How to pass JavaScript variables to PHP?
I created a facebook app recently that posts some content to the user group. If the user posts to multiple groups then I would like to display a progress bar. The HTML part of it I created a form that has got a text area and the form redirects to a post.php file. And I post to the user groups in that post.php page. As I said I use a progress bar to show the progress. But the message gets posted first and only then the progress bar works. I'm pretty sure about the progress bar that it works.
To put it short the PHP part gets executed first before the JS or the HTML. So please do help me out in overcoming this problem.
This is what I have in the post.php file :
<body style = "background-color: #4ea6e6;">
<center>
<div style = "width: 50%; margin-top: 5%; padding: 50px; background-color: #fff;">
<div class="input-group" style = "height: 30px;">
<progress min = "0" max = "100" value = "50" style = "height: 30px;">
</progress>
<span class="input-group-addon">
0%
</span>
</div>
<br>
<div class = "message">
</div>
<br>
<div class = "alert alert-success success" style = "font-size: 18px; font-family: Muli; visibility: hidden;"><b>Great !</b> Your message was successfully posted !</div>
</div>
</center>
</body> <?php
require_once 'libs/facebook.php';
$config = array(
'appId' => 'My app id',
'secret' => 'my app secret',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$groups = $_POST['groups'];
$link = $_POST['link'];
$message = $_POST['message'];
$count = count($groups);
for($i=1; $i<count($groups); $i++){
$api = $facebook->api($groups[$i] . '/feed', 'post', array(
link => $link,
message => $message
));
$api = $facebook->api($groups[$i]);
$name = $api['name'];
$j = ($i/(count($groups)-1))*100;
?>
<script type = "text/javascript">
var timeout = setTimeout(post, 0);
function post(){
$('progress').attr("value" , "<?php echo $j; ?>");
$('.message').html("Posting to <?php echo $name; ?>");
$('.input-group-addon').html("<?php echo $j; ?> %");
if(<?php echo ($i/count($groups)); ?> != 1){
var timeout = setTimeout(post, 0);
}
else{
clearTimeout(timeout);
}
}
</script>
<?php
}
You can't execute sync PHP after html and js are loaded.
BUT you can execute an XHR call to a PHP script so that once js is loaded the AJAX call starts and PHP script is executed in background
Here is how to use AJAX with jQuery
You can execute a separate PHP file after the page has loaded, without JS, like this.
Notice that the "background image" is actually a PHP file. The PHP file will execute when it is called at the bottom of the body, after the html file and all elements above it.
You can send data to the PHP file via GET in the CSS property...
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#runPHP
{
background-image:url(script.php);
display:none;
}
</style>
</head>
<body>
<div id="runPHP"></div>
</body>
</html>
I'm really new here. Hopefully this title makes sense.
My problem is: after I clicked either good.png or bad.png as a button, the js works well, but after I click the OK in the alert window, the image will disappear. It will show up again after I refreshed the page.
Here is real page for code: http://bit.ly/1iUjnlW
How could I fix this? Thank you very much !
(sorry for my bad language)
This is part of my code:
=========js function========
<script type="text/javascript">
$(function() {
$(".rate").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up'){
//$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "../data/rate_up.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
} });
}
else
{
//$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "../data/rate_down.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
} });
}
return false;
});
});
</script>
========img buttons in a table===========
<p class="p1">
<fieldset>
<legend>Sighting Detail</legend>
<div id="scroll_detail" style="overflow-y:auto; height:600px;">
<table>
<td>Rate this sighting: </td>
<td>
<div class="box">
<img src="../images/rating/good.png"><?php echo $up; ?>
</div>
<div class="box">
<img src="../images/rating/bad.png"><?php echo $down; ?>
</div>
</td>
</tr>
</table>
</div>
</fieldset>
</p>
</div>
</div>
<!-- Above is the website main files -->
<?php include ('../footer.php');
You are replacing your anchor tag's (which holds yiur image) inner html with html from AJAX response
parent.html(html);
try to alert the html returned from your AJAX before you replace the content and see what it contains
try appending the html returned
parent.append(html);