I am developing mobile applications, and I was thinking, if I need to download a picture from a server, I cannot actually run the PHP natively (I am using a PhoneGap type setup), so how could I download a picture from a database, run it though JavaScript and then display it to the user?
I would imagine something like:
Ajax request,
Return HTML string of binary data
Do some stuff to that?
Or
Ajax request,
Return a HTML string of reference to the picture, for example: picture1.jpg.
In JavaScript, write something like document.write <img src="http://blahh/img/"+imagePath
I'm not sure what the best way to do this is.
To my mind, the simplest way to dynamically load external pictures is to get a JSON object from a PHP script containing the picture URL (like http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID).
Server side
<?php
$pictureUrl = 'http://example.com/pictures/picture.jpg'; //You can get it with a database query
$pictureName = 'Foo';
$pictureAltText = 'Bar';
// You can do some stuff here.
// At the end of the script, write result.
echo json_encode(compact('pictureUrl', 'pictureName', 'pictureAltText'));
?>
Client side
<script type="text/javascript">
// With jQuery
$.getJSON('http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID', function(data){
console.log(data.pictureUrl, data.pictureName, pictureAltText);
var img = new Image();
img.src = data.pictureUrl;
img.setAttribute('alt', data.pictureAltText);
img.onload = function(){
// Displaying picture when download completed
$(img).appendTo('body');
}
});
</script>
If you don't use jQuery, you have to use XMLHttpRequest to get the JSON encoded response and to parse it (you can see the MDN documentation at https://developer.mozilla.org/en-US/docs/JSON).
You can do this, but not purely in JavaScript.
Since you mentioned PHP, I will go in that direction:
make table in database in which you will store all images. You need
to have some kind of image_content field and load every image in
some baseline64 encoder like:
http://www.motobit.com/util/base64-decoder-encoder.asp. And store
returned string into that image_content field.
Or you can write some script that will convert all images you want
to Base64 directly in PHP by using http://php.net/manual/en/function.base64-encode.php.
make a PHP file. For example, giveme_encoded_img.php in that file you
need to have one parameter in the URL like gimme_encoded_img.php?image_name=header_bg.
Then get image_name with $_REQUEST and do a MySQL query with that
data in the WHERE statement so that you can select an encoded image string
from the database.
After that, just print it.
When you do an Ajax request to a file above, just update the desired
image src with the response. The best way for doing this is to take the response
and get some element by id, like
var header_bg = document.getElementById('header_bg'); header_bg.src
= response;
The final HTML needs to look something like this:
img alt="Embedded Image" id="header_bg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..."
Baseline64 embedding is really good, especially if you need to embed images in emails, then a lot of email clients show them by default instead of hiding the remote images from your server.
I hope I was clear enough.
Still this is not a purely JavaScript solution.
Related
I've read many posts that due to security risks you cannot upload to your server with an image from your folder as javascript isnt allowed such access. However, I have a situation where i have an svg image on a web site that I convert to a png whilst on the website. But, I wish to send the converted image to my server.
Will I encounter the same problems as if I were uploading from my documents?
I tried to make an example of jsfiddle but it seems it doesnt accept document.write very well, so here's sort of a work-around:
DEMO: jsfiddle
Ideally we would have a button defined as so:
<button id="image" onClick="image()">Convert & Send</button>
Then have the code that does the conversion within a function along with the ajax
function image() {
//conversion code & ajax
}
So in conclusion I would just like to know if this is possible if not, i would be grateful if you could show an alternative way, whether it may include a combination of php.
thanks in advance
It seems as though the fiddle isnt loading heres the snippet: of the conversion
function image () {
var svg = document.getElementById("svg-container").innerHTML.trim();
var canvas = document.getElementById('svg-canvas');
canvg(canvas, svg, { renderCallback: function () {
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
}
});
I'm not sure about what your question is, but indeed, you can use a combination of Ajax + PHP to upload your image.
The client would POST an encoded image (e.g. encoded in Base64) using ajax (using jQuery.post, for example), while the PHP would receive the image and store it (after decoding it) in your server.
For an example of the process, check this question, where a specific case of a canvas is discussed. I think your SVG conversion could work in a similar way.
PS: For some reason, I couldn't load your Fiddle.
EDIT:
So both Ajax & PHP are written on the front end to send the image to
my server/database (ruby on rails). Is that correct?
No. Only Javascript (with Ajax) is used in the client. PHP would be the server part of the process, so in your case it would not be used as you are already using Ruby on Rails. In other words:
The client (browser) uses Javascript (maybe JQuery) to POST the image data (in your snippet, img) to the server (more info here).
The server (a PHP, ASPX or Ruby script [among others]) gets the POSTed data and saves the picture on disk (some info here).
If you can use PHP (in the server) for the specific process of saving the image, you can use the question I linked before as a guide.
Yes Of Course Their are ways:
I know 2:
1-(This One I know it works on chrome and Firefox but don't know IE):
First Get The Base 64 Data Of An Image In Canvas:
<canvas id="Canv" ....(Other Attributes)>
Your Browser does not support the canvas element :(
</canvas>
<button type="button" OnClick="Image()">Transform and Save</button>
<script type="text/javascript>
var can =document.getElementById('Can');
var ctx = can.getContext("2d");
//do something with ctx
function image(){
//You Should check the real format using img.src
var data = can.toDataURL("image/png");
var array = data.split(".");
var Base64Data = array[1];
//Now step 2 :Sent it to PHP
//Check for Browser compatibly
var ajx = new XmlHttpRequest()
ajx.onreadystatechange=function()
{
if (ajx.readyState==4 && ajx.status==200)
{
if(ajx.ResponseText == "Err"){//if the paged returned error
alert("An error Has Occurred");
return;
}//if not
alert("Saved Succesufuly");
}
}
ajx.open("GET","Save.php?q=" + Base64Data , true);
}
</script>
Step3: Interprete it With PHP
<?PHP
if(isset($_GET['q] And !Empty($_GET['q'])){
try {
$Data = $_GET['q'];
$hndl = fopen("Saved/Pic1.jpg" , "w");
fwrite($hndl , $Data);
fclose($hndl);
}catch(Exception $err){
echo "Err";
}
}else {
echo "Err";
}
?>
Yeap And That it.:D
You Could also loop throught each file in that directory and create a load button that get the Base64 Value And the first stuffs and out it into canvas using pucontent method of canvas element object
I use jquery to set a get query to a php script which then queries the database and writes to the screen, but I can't get it to trigger the download, even with headers.
The steps are as follows:
create a link that the user clicks to download the data
javascript sends the query parameters to php
php queries the database and writes the file
client downloads the file
But I can't get step 4 to happen.
Step 1: (this is a table object that also contains the parameters:
d3.select("#some-div").append('a")
.attr("href", "javascript: void(0)")
.on("click", function() { this.saveAsCSV() };
Step 2: Javascript file to make query:
var saveAsCSV = function(params) {
var tmp_params = $.extend({}, params);
tmp_params['State'] = "NM";
$.get('php/get_data.php', tmp_params);
}
php to return query:
...
header("Content-type: application/text-csv");
header("Content-Disposition: attachment; filename=query_result.csv");
while($row = $result->fetchArray() {
print "$row";
}
...
It works fine in that it correctly queries and will print the data in the javascript function (so it will print it to console.log if I add that into the get return function), but I can't figure out what I should do differently to make it just download it directly.
One thing I've tried is to do the following on the params object:
var param_string = encodeURIComponent(JSON.stringify(params));
location.href = 'http://www.mysite.com"+param_string;
But that both takes the user away from the page and fails to download the data.
EDIT: I should clarify that the php file does output the query well in csv format. The problem seems to be that using the $.get() function does not trigger a download regardless of the php headers. Maybe I need to just provide a simple link with the parameters in the URL address, but I'm not sure how to get a javascript object into a URL format so that the php script can interpret it.
You could open a popup/new window/tab/whatever with your URL php/get_data.php?State=NM (perhaps additional parameters). It should download the output.
But your output might be wrong because you just print the variable $row which is an array. If you try to print an array that way it will just show Array.
You will need to properly output your rows. Unfortunately I don't know the CSV structure well enough to help you with that problem.
You can make an AJAX call for this using something like jQuery and it will pop up the download box while keeping the user on the page. Do something like this:
$.ajax({data: {download: 'query_result.csv'}, type: 'GET', url: 'download.php', cache: false });
I've tried this a few times for a previous employer and it always worked great. Although I did it mostly with .zip and .docx files.
I figured it out!
Basically, my encoding was wrong. I don't want to encode with
encodeURIComponent(JSON.stringify(params));
The result isn't readable by the php script. However, it works to just use $.param().
To summarize, the download is triggered by creating the URL link and then using location.href to link to it. Hence everything else is the same, but instead of the $.get() in step 2, I do:
var url_params = $.param(tmp_params);
location.href = url_params;
Which generates the download. Thanks!
I am reading a rss feed with php and creating html DOM from the same. Now I have a bunch of <li>'s with news feed. when a user clicks on a particular <li> I want to post certain data to another php file which performs some other function.
How I want the data is tricky. I have a URL for all the feed elements. When a user clicks on a particular feed, I need to retrieve the URL associated with that particular feed.
I want to run a $.click() function in which I am going to $.post to the next php script.
How do I get that URL without storing it in the HTML itself. I do not want to store the URL in the html document for security puposes.
I am new with PHP.
You will need to assign unique id (uid) to each list element that corresponds to the url. A good way of handling this would be a database. You send the list item's identifier, look up in the database the associated url, perform some magic, and send the response back to the client. You can use jQuery's data method that leverages the html5 data attribute to store the information. Here is the basic pseudocode.
html
<li class="feed" data-uid="12345">Go</li>
javascript
$('li.feed').click( function() {
$.post({ id: $(this).data('uid') }, function(data) {
//do something with data
});
});
php
$uid = $_POST['uid'];
//db lookup of url
//do something with url
//return data to page
you could encrypt the url being sent from the server and then decrypt when it's sent back from the client. Just use a simple salt encryption method. I assume you're going to use ajax or the like to post back from the client to the server in which case, this methodology would work for you.
alternatively, you could create an array and store the urls in a collection with an associative key that you send to the client, then look up the url on the server side by that key. You could also implement a database solution to do this same thing where the key is the ID in the db.
U have to encode the variable url...
PHP
var url = ...;
JavaScript
$(function (){ var d1 = <?php echo json_encode(array($url)); ?>;});
I'm currently following this example for HTML 5 drag and drop. I am hoping to use this to upload the dropped files to a remote FTP server with a php script. However, how do my php script access these dropped files ?
With a regular web form, I can use $_FILES.. But I don't suppose I can use $_FILES for the dropped files..
On the example, the script calls handleFiles function after a drop event
function handleFiles(files) {
var file = files[0];
document.getElementById("droplabel").innerHTML = "Processing " + file.name;
var reader = new FileReader();
// init the reader event handlers
reader.onprogress = handleReaderProgress;
reader.onloadend = handleReaderLoadEnd;
// begin the read operation
reader.readAsDataURL(file);
}
I guessing that I can iterate each element of the array list, and send each element to my php script. As I've mentioned above, how can I send this element from the array list to the php script? JSON ? jQuery POST ?
I am aware that there are various jquery plugins available to achieve this, and I have downloaded a few of them... However I'm just curious to know if I can implement the same thing with this example.
I presume by upload you mean upload it in a ajax operation.
file refer to a File object, which is available for you after the user had drop the file. After that you have two options:
Read the file using FileReader, send the text in xhr as post data (not recommend as it only work with text)
Pass the object to FormData then pass the FormData object to xhr to send the file (Doesn't work with Firefox <= 3.6 though)
Check Mozilla Developer Center document for the usage of these interfaces. I have working projects that use these objects, however there are too much bridging code to be a good walk-through demo. https://github.com/timdream/html5-file-upload
Why not use an open source solution for your problem rather than re-inventing the wheel.
http://plupload.com/
Is pretty much all you will ever need. I use it and it works wonders. Also, it falls back onto html 4 form uploading when a browser cannot handle html5.
I need to set a PHP $_SESSION variable using the jQuery. IF the user clicks on an image I want to save a piece of information associated with that image as a session variable in php.
I think I can do this by calling a php page or function and appending that piece of info to the query string.
Any ideas. I have found little help through google.
thanks
mike
You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:
HTML:
<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />
Javascript:
$("img.foo").onclick(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});
PHP (backend.php):
<?php
// do any authentication first, then add POST variable to session
$_SESSION['imgsrc'] = $_POST['img'];
?>
Might want to try putting the PHP function on another PHP page, and use an AJAX call to set the variable.
Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.
A lot of responses on here are addressing the how but not the why.
PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript.
To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers.
I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.
I also designed a "php session value setter" solution by myself (similar to Luke Dennis' solution. No big deal here), but after setting my session value, my needs were "jumping onto another .php file". Ok, I did it, inside my jquery code... But something didn't quite work...
My problem was kind of easy:
-After you "$.post" your values onto the small .php file, you should wait for some "success/failure" return value, and ONLY AFTER READING THIS SUCCESS VALUE, perform the jump. If you just immediately jump onto the next big .php file, your session value might have not become set onto the php sessions runtime engine, and will you probably read "empty" when doing $_SESSION["my_var"]; from the destination .php file.
In my case, to correct that situation, I changed my jQuery $.post code this way:
$.post('set_session_value.php', { key: 'keyname', value: 'myvalue'}, function(ret){
if(ret==0){
window.alert("success!");
location.replace("next_page.php");
}
else{
window.alert("error!");
}
});
Of course, your "set_session_value.php" file, should return 'echo "0"; ' or 'echo "1"; ' (or whatever success values you might need).
Greetings.
in (backend.php) be sure to include include
session_start();
-Taylor
http://www.hawkessolutions.com
Similar to Luke's answer, but with GET.
Place this php-code in a php-page, ex. getpage.php:
<?php
$_SESSION['size'] = $_GET['size'];
?>
Then call it with a jQuery script like this:
$.get( "/getpage.php?size=1");
Agree with Federico. In some cases you may run into problems using POST, although not sure if it can be browser related.
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});