Simplest way for image upload function , without refreshing page - javascript

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.

Related

Pass Javascript variable to another page via PHP Post

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!

php, css, javascript: click on image -> change the image -> call function

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

Including imagegrabscreen php function to a button onclick without refreshing the page

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

How to clear a server-side html file's content, from input type button

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", "");
}

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories