Change image src without refreshing from mysql database - javascript

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.

Related

php Load an Image from url with json and display

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.

Can't change span content inside a td HTML using js/php

I have a php snippet on Wordpress that contains a loop through my SQL that will create a table for user.
On that PHP code, i have a specific var that needs to get a X value from web, i was using PHP to do all of it, but since it's not async, it causes page load to be 10s~
I tried use jQuery/JS, unfortunately, i couldn't change value inside <td>
$charstatus = "
<script>
$.get('isOnline.php?name=".$jsName."', function(data) {
var element = document.querySelector('".$vps.$slot."')
element.innerHTML = data
});
</script>";
Why won't it work?

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.

How to change an image on a site using XML data & jQuery

I have a site that has a banner at the top of the page. I've started to overhaul my HTML structure and am now getting various pieces of information that populate the site out of an XML file. My HTML that uses the jQuery is:
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
<script>
var root = null;
$(document).ready(function ()
{
$.get("Status_Pages.xml",
function (xml)
{
root = $(xml).find("site[name='" + exampleSite + "']");
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
var imageSrc=$(root).find("headerImage").text();
$(".PageHeader img").attr("src",imageSrc);
result = $(root).find("version");
$("td#version").html($(result).text());
result = $(root).find("status");
$("td#status").html($(result).text());
result = $(root).find("networkNotes");
$("td#networkNotes").html($(result).text());
....etc etc
});
});
</script>
My XML file looks like this.
<sites>
<site name="Template">
<headerImage>images/template-header.png</headerImage>
<productVersion>[Version goes here]</productVersion>
<systemStatus color="green">Normal</systemStatus>
<networkNotes>System status is normal</networkNotes>
</site>
</sites>
I have several <site>s that all have their own data that will populate different areas of individual sites. I've ran into some snags though.
The first snag is how it currently obtains its header image:
html
<div class="container">
<div class "PageHeader"> <!-- Header image read from XML file -->
<img border="0" src=""/>
</div>
Right now it's hard-coded to be the template header image, but I need to make that generic and read the XML value for that site. So instead of being hard-coded as images/template-header.png it would read the XML value for the current site, which is still going to be the template header - but it won't for every page.
How can I read in the image string to populate my HTML so that each site has a different image depending on what's in the XML?
Edit: Edited code to match current issue. Currently, I just get a broken image, but I can still change it back to the hard-coded image URL (images/template-header.png) and it works.
As you already have the code that can extract the image URL information from the XML, which is
result = $(root).find("headerImage");
$("td#headerImage").html($(result).text());
It's now a matter of attaching that URL, to the image tag. We need to select the object, and then simply change it's src attribute. With jQuery this is actually pretty easy. It'll look something like
var root = $(xml).find("site[name='" + site + "']");
//get the image url from the xml
var imageSrc=$(root).find("headerImage").text()
//get all the images in class .PageHeader, and change the src
$(".PageHeader img").attr("src",imageSrc)
And it should work
Example
In conclusion, if you already have some values you want to put in HTML tags dynamically, it's pretty easy. There's .html("<b>bold</b>") for content, there's .attr("attrName","attrValue") for general attributes. .css("background","red") for changing CSS directly. There's also some class modifying stuff that would be useful in the future.

jQuery to change element Attributes and return the edited Html Source back?

Actually what i'm doing is to find the <img> image tags and get its src attribute to change them.
I already got upto this point but the problem more is: To get the edited the html source back (to put into the database.)
To say more brief & clearly, i'm about to grab some Dynamic Html Containers and then change the image paths and save the whole source chunk back.
For brief example if i search inside $(div.container).html() on this:
<div class="container">
<..> .. </..>
<..>
<img src="images/apple.jpg" />
<..>
<img src="images/banana.jpg" />
</..>
</..>
</div>
Firstly, lets say <..> represent any of not previously knowable html tags.
Then i will get:
var dom_contents = $("div.container").html();
Now i got the original html source inside the target container <div>
Then lets say i need to change each <img src with sample/ for its folder. It will then be fruits/apple.jpg and fruits/banana.jpg.. etc.
I still getting some of the stuffs like:
$("div.container).each(function() {
var arr = $(this).find("img");
for (var i=0; i<arr.length; i++) {
var img_src = $(arr[i]).attr("src");
/*
* I NEED TO CHANGE THE IMAGE SRC HERE
*/
}
});
** Finally, i need to save this the whole edited html source into the database. **
So how do i change the <img src='' .. and
How do i get this whole edited html source, back from the jQuery?
Amend the source attribute for each image as follows. You don't need to write the html back. The source html will be updated:
$("div.container").each(function() {
$(this).find("img").each(function() {
$(this).attr("src", "/image/url/file.png");
});
});
To get the html source of the container, use the following:
$("div.container").html();
This will set the attribute:
$(arr[i]).attr("src", mynewsrcvalue);
Once you're done just send the innerHTML (or .html()) back in an AJAX request. But if you want this stuff in a database, why not just manipulate the source on the server side in the first place?

Categories

Resources