I'm trying to create a button with an onclick function that activates the imggrabscreen php function. Problem is, I've done several codes and so far the only function that I was able to use was a submit input type in which this refreshes the page. I tried using button as an input type but unfortunately, it does not save any screenshots upon clicking the button. Here's the code that I'm using so far.
if(isset($_POST['btnscreen']))
{
$im = imagegrabscreen();
imagepng($im, "screenshot.png");
}
ob_end_flush();
?>
<form method="post" action="" enctype="multipart/form-data">
<br>
<input type="submit" value="Click to Screenshot" id="btnscreen" name="btnscreen"></center>
<br><br>
</form>
php is parsed and executed server side (pre-processing) so you cannot call any php functions after the page has been sent to the browser. The only way to do this is to make a new request to the server (ajax).
I can't quite grasp what your function does (php cannot make a screenshot of what your browser is displaying as it has no information of how it has been rendered - please note different browsers may display the page differently).
I would try reading up on html5 canvas element which can achieve that (e.g. https://html2canvas.hertzen.com/).
Hope this helps
Related
I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!
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
I am working on a popup newsletter signup. I already have the similar signup form in another page. I used the exact code and it works great. Once I submit the form, two actions has to happen.
Sending the form details to database
Redirecting to thank you page.
With the existing code(this is from a ecommerce website, I cannot manipulate the code), I can send the details to database - perfectly works fine, but
it is not redirecting to Thank You page, instead redirecting to the page hardcoded in the database(assigned to "action". Is there a way out?
This is the code.
<form name="MailingList" method="post" action="http://www.mywebsite.com/MailingList_subscribe.asp">
<input type="text" name="emailaddress" placeholder="Email Address" maxlength="100" size="28"> <br>
<input type="submit" name="Submit" value="Submit" width="260px">
</form>
Instead of this - http://www.mywebsite.com/MailingList_subscribe.asp, I would like to redirect to "www.mywebsite/thankyou.html" . If I assign www.mywebsite.com/ThankYou.html to "action" , then the form is getting redirected to Thank you page, but not sending the information to the database. I have to use HTML, I cannot call from outside file. I guess I need to use PHP, but I am unclear with the code.
Sorry my mind is all over the place, I guess I explained it clearly. Apologies if my question is unclear. Thanks
Give id to your form like formId and you can do this using jQuery,
Download the jQuery latest version from JQuery repo and then place the jquery.min.js file in your resources folder.
Updated
<script src="yourResourcesFolderPath/jquery.min.js"></script>
// above code will use the jQuery plugin online
// chances are that the file path might be wrong according to where you put the js file
// A simple way to try this is put your file in the same folder of your html file and then change above code to
// <script src="jquery.min.js"></script> change file name according to downloaded file name.
<script>
$(document).ready(function(){ // will run the below code after all html loaded
$('#formId').submit(function(){ // will be called upon form submission
$.ajax({
type: "POST",
url: "http://www.mywebsite.com/MailingList_subscribe.asp",
context: document.body
}).success(function() {
// this will be called when you return from your server submit code
location.href = "www.mywebsite.com/ThankYou.html";
});
});
)};
</script>
Here's a challenge:
I don't care about which language to use, Javascript, PHP, .. whatever.
I need the most simple way to let my user upload an image.
I will later offer the user a way to place it on a canvas (displayed inside a div, with jquery draggable)
I can not have the page refreshed since there are useful variables in other fields etc..
(I don't have any security preferences as this will be a local website for intranet)
I tried:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
</br>
<input type="file" name="file" id="file" size="70%"><br>
</br>
<input type="submit" name="submit" value="Submit">
</form>
But then came to realise there are soo many options out there, such as uploadify, and i easily got lost online..
You have two choices to make a file upload w/o refreshing the page:
Use HTML5 form upload
Post the form to an hidden iframe
The latter one gives best browser compatibility, and is what I'd suggest you to use. To post to an hidden iframe, simply set the target of the form to the iframe:
<script>
// Global callback function from the file
function uploadCallback(){
console.log("File is uploaded!");
}
</script>
<iframe name="hiddentarget" style="display:none;"></iframe>
<form action="upload_file.php" method="post" enctype="multipart/form-data" target="hiddentarget">
...
To respond back to the site from the iframe, you will have to go through the window.top frame as such:
upload_file.php:
<?php
// Uploading stuff
// ...
// "Talk" back to the site
// Of course you can (should) pass some parameter to this JS-function, like the filename of the recently uploaded image.
echo "<script>window.top.uploadCallback();</script>";
?>
EDIT:
As suggested by other users; the optimal solution would be to use the File API where supported, and fall back to the hidden iframe on browser that doesn't support it. This gives you nice features such as file uploda progress for example.
The way that I would suggest is using AJAX and and make your upload box a div which can be replaced when the upload is successful. Instead of traditional post you then create a Javascript function for onSubmit. Your action can then be changed to #.
If you lookup AJAX there are some great tutorials about and you will be able to do many more amazing things.
Alternatively look into jQuery which will definitely have something to help you
I'm gonna show you an example on how to use the jQuery Form Plugin to upload files to your server really easy without needing to refresh the page.
First off, download and install the jQuery Form Plugin. After you do that, include it in your files where you want to make use of it. Add an ID attribute to your form tag like this:
id="unique_id"
After you have identified the upload form, put this code in your jQuery:
$(function() {
$('#unique_id').ajaxForm({
target: '.myTarget' // Display here whatever the server side script returns
success: function(response) {
// An usual success callback
}
})
})
Assuming that your server side language is PHP, this is how a simple upload script would look like (upload_file.php):
<?php
$uploaddir = 'your_upload_dir/something';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']); // Filename
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo $uploadfile;
} else {
echo "Error";
}
?>
Where userfile is the name attribute of your file input (<input type="file" />).
The above code combined returns the relative path to your image which you can use to display the image inside an img tag. You must use Javascript (or jQuery) for that.
I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}