php Load an Image from url with json and display - javascript

I want to get images from URL I am very very new to JavaScript. I appreciate your patience with me.
I'm trying to create a script that allows a user to input a name into a text-area, press submit and an image is displayedon web page based on imei no.enter image description here
{"status":1,"image_list":["011975002649_201020131619.jpeg","011975002649_201020134737.jpeg","011975002649_201027135940.jpeg"]}

Assuming the files are uploaded on your server, and you want to print images with PHP you can do :
$images = array("image1.jpg", "image2.jpg");
foreach ($images as $image) {
echo "<img src='/path/to/images/$image' />";
}
Edit after discussion:
You must perform an XHR to getinfo.php. See: https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest
On server's answer then test for success or fail
if success parse JSON, and loop through the table to create an img element each time you want to display an image. See https://developer.mozilla.org/fr/docs/Web/API/Document/createElement
otherwise, handle error

Please try this code, To PHP Load an Image from URL and display
<?php
$image = 'http://www.google.com/doodle4google/images/d4g_logo_global.jpg';
$imageData = base64_encode(file_get_contents($image));
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
?>
I hope this code will be useful to you.
Thank you.

Related

PHP altering HTML on first connection

Currently I have a php-page using include to show an html-page.
What I want to do is use a variable the php-page received when being called and project data into a field of the html-page depending on this variable. The problem is that I can't seem to pass the variable from php to html without using html to call php.
I know that I can simply echo the php-part, but because I can't echo straight into one of the html-page's divs it ends up putting the echo at the beginning or end of the page.
What I want to accomplish is for the html-page to load the php-part into one of the div's the first time the php includes the html-page. Is there any way to do such a thing?
If this isn't possible, then how do I get the javascript in the html-page to use the variable from the php-file? Is the best option really the href?
As requested some of the code:
php:
if (filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING))
{
include "../Html/EventPage.html"; //target page
$temp = filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING); //get the variable
include "../PHP/Connector.php"; //include the connection page
$value = callFunction(Connect(), $temp); //call connection page and return value
echo "<div class = 'cant select div in html'>" . $value . "</div>"; //echo value in location
}
html:
<div id = "dynamic">
this should have the php
</div>
I assume you use some code like this to display the page:
include('page.html');
A safer way would be to prevent evaluation in page.html:
echo file_get_contents('page.html', true);
You can then do any string modification you want for the content:
$replacement = 'MY REPLACEMENT';
echo str_replace('<div id="my-div">', '<div id="my-div">' . $replacement, file_get_contents('page.html', true));

echo variable to document via button click

First time here so apologies if I'm doing something wrong.
I have the following php code:
<?php
$quoteFile = "quotes.txt"; //File holding qoutes
$fp = fopen($quoteFile, "r"); //Opens file for read
$content = fread($fp, filesize($quoteFile));
$quotes = explode("\n",$content); //Put quotes into array
fclose($fp); //Close the file
srand((double)microtime()*1000000); // randomize
$index = (rand(1, sizeof($quotes)) - 1); //Pick random qoute
?>
The code fetches a random quote from a text file by randomly choosing one of the lines of the .txt file.
I then echo out the result using:
echo $quotes[$index];
However what I want to achieve and don't seem to be able to is to have a button (html) that when clicked executes the echo $quotes[$index]; to the current page. So that each time the button is clicked it prints/echo's out a random quote from the .text file.
I did mess about with just setting a button up to refresh the page which by default made a new random quote display but it sometimes just reloaded a blank so I'm hoping someone can help me achieve this better or prompt me in the right direction. Thank tou.
You can try saving that variable into a session variable like this:
$_SESSION['quote'] = $quote['index'];
Then create an anchor element that redirects to current page:
Refresh
And print the result on the page:
<span><?php echo $_SESSION['quote']; ?></span>
To do all of this, you need to set a session. At top of your php file write:
session_start();
Hope that helps. :)
Your TXT file might have an empty line in it at the end or anywhere else. A second explanation of this, is that the way you are generating randomness is quite questionable.
Check out this simple example by W3 Schools.
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,1);
echo $a[$random_keys[0]]."<br>";
The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.
Or, simply:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>
Full Post: http://www.w3schools.com/php/func_array_rand.asp
Happy coding !

editing html with embedded PHP using javascript

I hope someone has an answer for me,
I am currently trying to create a PHP product page for my shop website, I have an sql table that stores the name of an image prefix eg if the image file is 'test_1.png' then the table stores 'test'. using embedded php
src="images/shop/<?php echo $row['item_img'], '_1.png';?>"></img>
what I would like to do is using js, dynamically update the src on a mouse click.
something like eg.
var imgSwitch = function(i){
Document.getElementById('js-img').src = "images/shop/
<?php echo $row['item_img'], '_';?>i<?php echo '.png';?>";
}
Even to me this seems wrong which is why I've turned to the GURU's here
Is there anyway this would be possible? If not, any suggestions would be GREATLY appreciated
I am trying to figure out what you are asking, and I think this is your way to go:
var imgSwitch = function(i){
document.getElementById('js-img').src = "images/shop/<?php echo $row['item_img'], '_';?>" + i + ".png";
}
The change is in the i, you have to cut the string and add it as a variable.
But remember that the PHP code is executed at the server, and will not change once the page is sent to the client. When you execute that function, $row['item_img'] will always be the same.
A simple example which you can adapt. What I do in the code below is give the element an id and attach an onclick to it.
In the function we pass the id as a parameter (onclick(changeSrc(this.id))) and we manipulate the src using the getElementById as we have the id.
<img src="http://ladiesloot.com/wp-content/uploads/2015/05/smiley-face-1-4-15.png" id="test" onclick="changeSrc(this.id);" height="400" width="400" />
<script>
function changeSrc(id) {
document.getElementById(id).src = "http://i0.wp.com/www.compusurf.es/wordpress/wp-content/uploads/2014/04/smiley.jpeg?fit=1200%2C1200";
}
</script>
http://jsfiddle.net/tq1Lq5at/
Edit 1
You're using Document when it should be document, notice the lowercase d.

Preload all images in a directory using jQuery

I want to preload all images in a directory called img,and that directory also contains sub directory called ui_images.
I know how to preload specific images by putting their names in an array and doing the preloading work, but i want to know how to tell the script to search dynamically for all images in that directory img and img/ui_images?
Here's my code :
var preloadImg = function(imgArr){
$.each(imgArr, function(index,value){
$("<img/>")[0].src = value;
});
}
var arrimg = ['img/check.png','img/add_sub.png'];
preloadImg(arrimg);
There is no generally available facility for doing a directory listing in http. The options I can think of are:
Name your images in a predictable fashion like (img001, img002, etc...) and then you can load images until you get an error.
Name your images in a predictable fashion like (img001, img002, etc...) and then code in one numeric limit value into your web page for how many there are.
Create an ajax call (on both client and server) that will give you a list of image names to preload.
Have your server embed an array of image names into the page so you know what to preload.
I was looking at improving the performance on one of my sites and looked into this. My solution seems to work and I haven't seen it anywhere else yet.
Its a two step approach using jquery and php
// Preload images via jquery .load and delete once their cached via the callback
<div id="preload"></div>
$('#preload').load('preload.php', function() {
$('#preload').remove();
});
// preload.php below - loop through the image folder and insert the images into a hidden div
<div style="display:none">
<?php
$dirf = 'images';
$dir = scandir($dirf);
foreach ($dir as $file) {
if (($file != '..') && ($file != '.')) {
echo "<img src='images/$file' />";
}
}
?>
</div>
This worked in Firefox but feel free to critique or improve

Change image src without refreshing from mysql database

I am a bit of a pickle right now: I have an image displayed on my website, which has an src from a mysql server, it looks like this:
echo '<img src = "'.$sourceVariableFromDatabase.'" class = "profileImage" id = "profilePicture" />';
Also on my site, is a function that changes the database, and hence the value of $sourceVariableFromDatabase. However, the image won't update until the page is refreshed, but I would like it to display the new image src from the databse without refreshing.
I know this can be done through jQuery, but am unsure as to how to get the value from a database, as Javascript is not a server side, like javascript, and as far as I know cannot access databases in mysql.
How can I achieve this in Javascript/jquery.
Thanks, I have tried to be as clear as possible, and apologise for any waffle.
JQuery can be used to call a URL that returns data (e.g. HTML, JSON, text, etc). How that URL returns data can be however you want (PHP+MySQL, etc). Once JQuery receives the response, it can then update the img tag.
Here is a simple example:
Example HTML
<img id="profilePicture" src="(your source from db1)" />
Example JQuery on HTML page
function update_image(db)
{
// get new image src
$.get('some/url/to/get/new/src', {db: db}, function(response){
// update the img src
$('#profilePicture').attr('src', response);
});
}
Example page (/some/url/to/get/new/src):
<?php
// get request data
$db = $_GET['db'];
// get img src
$src = some_function_to_get_src($db);
// output src
echo $src;
$.get('/pathToCode', function(imagePath){
$('#profilePicture').attr('src', imagePath);
});
The file at /pathToCode would need to query the database and echo the path to the image. Just add this code to the end of your function that changes the database.

Categories

Resources