PHP Set Roblox Avatar to Image - php

I've been trying to figure this out for like 3 hours and am not getting anywhere. I'm trying to set the img src in the avatar div to the Roblox user's avatar URL with this endpoint https://thumbnails.roblox.com/v1/users/avatar-bust?userIds=3102777127&size=150x150&format=Png&isCircular=true but it requires usernames and my data is usernames so we have to use this endpoint to get IDs https://api.roblox.com/users/get-by-username?username=VOICECHAT22983. I have been trying a bunch of different stuff and nothing is working and just getting a bunch of errors.
This is how the data looks:
brenda12322323
eunaodoaisnudhnac
Lovesroblox1334
Cho5963
Sinmin191
vikaa_qwixxk
yourfav_stepsister
SnipesG0D
This is the PHP Code
<?php
$lines = file('../txt/names.txt');
foreach ($lines as $line) {
echo '<div class="avatar">
<img src="'.$avatar.'" alt="">
<h1>' . $line . '</h1>
Profile
</div>';
}
?>
I'm trying to set the $id variable as the user's ID and the avatar variable as the image URL

You need to get all the IDs first from the get-by-username endpoint, pass those into the avatars endpoint, then put the data back together:
<?php
/*
Question Author: cdnAshton
Question Answerer: Jacob Mulquin
Question: PHP Set Roblox Avatar to Image
URL: https://stackoverflow.com/questions/74977675/php-set-roblox-avatar-to-image
Tags: php, roblox
*/
function get_id_by_username($name)
{
$url = 'https://api.roblox.com/users/get-by-username?username=' . $name;
echo 'getting ' . $url . PHP_EOL;
return json_decode(file_get_contents($url), true);
}
function get_avatar_urls($ids)
{
$ids_param = implode(',', $ids);
$url = 'https://thumbnails.roblox.com/v1/users/avatar-bust?userIds='.$ids_param.'&size=150x150&format=Png&isCircular=true';
return json_decode(file_get_contents($url), true);
}
if (!file_exists('users.json')) {
$names = file('names.txt');
$users = [];
foreach ($names as $name) {
$name = trim($name);
$id = get_id_by_username($name);
$users[$id['Id']] = $id;
sleep(15); // Needed otherwise you will hit API rate-limits
}
file_put_contents('users.json', json_encode($ids, JSON_PRETTY_PRINT));
} else {
$users = json_decode(file_get_contents('users.json'), true);
$ids = [];
foreach ($users as $user) {
$ids[] = $user['Id'];
}
$avatars = get_avatar_urls($ids);
foreach ($avatars['data'] as $avatar) {
$users[$avatar['targetId']]['AvatarUri'] = $avatar['imageUrl'];
}
file_put_contents('users.json', json_encode($users, JSON_PRETTY_PRINT));
}
The script is executed twice, the first time it will read the names from names.txt, and get the IDS, saving into a users.json file. Then when you execute it again, it will get the IDs from the JSON file, then call the avatars and then merge it back together. The result is a JSON file like so:
{
"3528175625": {
"Id": 3528175625,
"Username": "brenda12322323",
"AvatarUri": "https:\/\/tr.rbxcdn.com\/3c195f46b44d37aa250c0d7c6ae41ded\/150\/150\/AvatarBust\/Png\/isCircular",
"AvatarFinal": false,
"IsOnline": false
},
"4028593775": {
"Id": 4028593775,
"Username": "eunaodoaisnudhnac",
"AvatarUri": "https:\/\/tr.rbxcdn.com\/0fc96af99739e29c780af459db6c2bd8\/150\/150\/AvatarBust\/Png\/isCircular",
"AvatarFinal": false,
"IsOnline": false
}
}
Then to output this information on a webpage:
$users = json_decode(file_get_contents('users.json'), true);
foreach ($users as $user) {
echo '<div class="avatar">
<img src="'.$user['AvatarUri'].'" alt="">
<h1>' . $user['Username'] . '</h1>
Profile
</div>';
}
Gives you something like this:

Related

PHP Traverse through JSON using foreach

I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. I am trying to grab coordinates from google geocoding API and stick them into Places for Web. I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work.
Here is the JSON object from the place search API
{
"html_attributions":[ ],
"results":[
{
"geometry":{ },
"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
"name":"Guadalajara Mexican Grill & Cantina",
"opening_hours":{ },
"photos":[
{
"height":2952,
"html_attributions":[ ],
"photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
"width":5248
}
],
"place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
"price_level":2,
"rating":4.4,
"reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
"scope":"GOOGLE",
"types":[ ],
"vicinity":"105 North Main Street, Lake Elsinore"
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"status":"OK"
}
I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. Here is my attempt at that:
UPDATE
<?php
if(!empty($_GET["location"])){
//$API_key = "";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($_GET['location']) .
'&key=';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
'location=$lat,$lng' .
'&radius=1500' .
'&rankby=distance' .
'&key=';
$places_json = file_get_contents($places_url);
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array as $item) {
var_dump($places_array );
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>What is Here?</title>
</head>
<body>
<h1>Type in a location</h1>
<p>This program will display pictures of places to go in that area</p>
<form action ="">
<input type ="text" name ="location"/>
<button type ="submit">Go!</button>
</form>
<br/>
<?php
echo "$lat $lng";
?>
Just can't seem to get the foreach loop to do anything
the invalid request means wrong url or bad parameters
if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this
"location=$lat,$lng"
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';
you should remove radius or distance you cant get both its on the docs
https://developers.google.com/places/web-service/search?hl=en-419
here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine
after that the foreach should be easy since is only an array look at the code
$thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($thelocation) .
'&key=' . $thekey;
$contextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array["results"] as $item) {
echo $item["name"]."<br>";
}
}
this prints....easy
AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group
The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second.
The json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. More about this.
There's no $item->photo_reference, use:
$results = $places_array["results"];
foreach ($results as $item) {
echo $item["photos"]["photo_reference"];
}

Html/Markup format using Picasa PHP FOREACH

Hi guys im trying to format an html output based on this picasa script using foreach, this way:
<? foreach($albums as $photo) {?>
<span><img src="<? echo $photo[1]; ?>" border=0></a><p><?=$photo[0]; ?></p></span>
<? } ?>
The output is:
<span><img src="foto1.jpg" border=0></a><p>This is pict 1 Album 1</p></span>
<span><img src="foto2.jpg" border=0></a><p>This is pict 2 Album 1</p></span>
<span><img src="foto3.jpg" border=0></a><p>This is pict 3 Album 1</p></span>
<span><img src="foto4.jpg" border=0></a><p>This is pict 4 Album 2</p></span>
But i need this:
<div>
<h1>Album 1</h1>
<span><img src="foto1.jpg" border=0></a><p>This is pict 1 Album 1</p></span>
<span><img src="foto2.jpg" border=0></a><p>This is pict 2 Album 1</p></span>
<span><img src="foto3.jpg" border=0></a><p>This is pict 3 Album 1</p></span>
</div>
<div>
<h1>Album 2</h1>
<span><img src="foto4.jpg" border=0></a><p>This is pict 4 Album 2</p></span>
</div>
The idea is bring all the album in my picasa account with their pictures inside, example:
album 1 has:
foto1.jpg
foto2.jpg
foto3.jpg
album 2 has:
foto4.jpg
So on ... That's it i hope someone could help me and understand better my really bad english :)
FULL SOURCE:
<?php
$userid = "cramosb"; // Your Google user name
$target = "PicasaBox.php/?album="; //URL to pass the name of the album to for the links
$imgmax = "512";
/*------------------------------------------------------------------------------
| USER CONFIGURATION END
------------------------------------------------------------------------------*/
// *** Only modify past this point if you know what you're doing ***
$insideentry = false;
$tag = "";
$title = "";
$url = "";
// function to parse the start of an XML element
function startElement($parser, $name, $attrs) {
global $insideentry, $tag, $title, $url;
if ($insideentry) {
$tag = $name;
if ($name == "MEDIA:CONTENT"){
$url = $attrs["URL"];
}
} elseif ($name == "ENTRY") {
$insideentry = true;
}
}
// function to parse the end of an XML element
function endElement($parser, $name) {
global $insideentry, $tag, $title, $url, $albums;
if ($name == "ENTRY") {
$albums[] = array($title, $url);
//echo $title . ' ' . $url;
$title = "";
$url = "";
$insideentry = false;
}
}
// function to parse the contents of an XML element
function characterData($parser, $data) {
global $insideentry, $tag, $title, $url;
if ($insideentry) {
if ($tag == "TITLE") {
$title .= $data;
}
}
}
// Lets get started...
// Create an XML parser, using the functions above
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
// The URL of the album feed I CHANGE THIS: $feed = "http://picasaweb.google.com/data/feed/api/user/" . $userid . "?kind=album"; TO:
$feed = "http://picasaweb.google.com/data/feed/api/user/" . $userid . "?kind=photo";
// Open the feed
$fp = fopen($feed,"r")
or die("Error reading RSS data.");
// Parse the feed
while ($data = fread($fp, 4096))
xml_parse($xml_parser, $data, feof($fp))
or die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
// Close the feed
fclose($fp);
xml_parser_free($xml_parser);
foreach($albums as $album)
{
$htmlout .= '<span><img src="' . $album[1] . '" border=0><p>' . $album[0] . '</p></span>';
}
print $htmlout;
exit;
?>
If you wish to split the output into 'albums' you need to know how to split the array of photos based on which album they should belong to. How are you populating $photo? Is each 'album' going to have only 3 photos in?
here, your homework done for you
<div>
<h1>Album 1</h1>
<? foreach($albums as $photo) {?>
<span><img src="<? echo $photo[1]; ?>" border=0></a><p><?=$photo[0]; ?></p></span>
<? } exit;?>
</div>
<div>
<h1>Album 2</h1>
<span><img src="foto4.jpg" border=0></a><p>This is pict 4 Album 2</p></span>
</div>
note the other answer as well. splitting out which "foto" goes into which album requires more information, this is just an example with html markup so you can understand how the php is fitting in the mix

Sending encoding response in json

I am using a lot of jQuery in a project am working on.
I have a javascript function that makes an ajax request to a controller which returns data in JSON.
I would like to display a user friendly message informing the user that he/she has no information stored yet. But I'm confused as to how to send a response in JSON so my javascript function can determine whether the user has information to be displayed.
Here is my javascript function:
function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$('#pheed-stream').html('<div class="loading"></div>');
$('.loading').append('<img src="'+pheed_loader_src+'" />');
$.ajax({
url:action,
type:'GET',
dataType:'json',
error: function () {
},
success:function(data) {
$('.loading').fadeOut('slow');
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p><a class="user_trigger" href="users/info/'+item.user_id+'">'
+item.user_id+'</a></p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span class="cm">'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'<span>'+item.repheeds+
' Repheeds'+
'<img class="repheed_trigger" src="/pheedbak/assets/img/communication.png" title="Click to repheed" onclick="repheed('+item.pheed_id+')">'+
'</span>'+
'<span>'+
'Favourite'+
'<img class="favourite_trigger" src="/pheedbak/assets/img/star.png" title="Click to make this a favourite" onclick="favourite_pheed('+item.pheed_id+')" />'+
'</span>'+
'</div>'+
'</div>'
);
});
}
});
}
And heres the controller function the ajax request is made to
function latest_pheeds() {
//Confirm if a user is logged before allowing access
if($this->isLogged() == true) {
//load the pheed model for database interaction
$this->load->model('pheed_model');
//load user model
$this->load->model('user_model');
//load comment model
$this->load->model('comment_model');
//store the pheeds to a the $data variable
$data = $this->pheed_model->get_latest_pheeds();
//Load the date helper to calculate time difference between post time and current time
$this->load->helper('date');
//Current time(unix timetamp)
$time = time();
//pheeds
$pheeds = array();
if(count($data) > 0 ) {
foreach($data as $pheed) {
$row['pheed_id'] = $pheed->pheed_id;
$row['user_id'] = $this->user_model->return_username($pheed->user_id);
$row['pheed'] = $pheed->pheed;
$row['datetime'] = timespan($pheed->datetime,$time);
$row['comments'] = $this->comment_model->count_comments($pheed->pheed_id);
$row['repheeds'] = $pheed->repheeds;
$pheeds[] = $row;
}
echo json_encode($pheeds);
$response['response'] = "Ok";
$res[] = $response;
echo json_encode($res)."\n";
}
} else {
}
It generates the JSON output,but the syntax is broken so i cant read it with javascript,
but once i get rid of the following code from the above method it works normally
$response['response'] = "Ok";
$res[] = $response;
echo json_encode($res)."\n";
You MUST only use json_encode($data) once in a response, if you want to output more stuff, you need to merge your data into one array and send that.
EDIT: To be clear, one way you could do it is like this:
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
Then in JS you will get an array with the keys "pheeds" and "res".
Although it may be of little practical significance, I would also recommend doing this before you echo the json encoded string:
header('Content-Type: application/json');

Bad array? Bad foreach?

Sorry for the huge ignorance on the topic, but I really have no idea where to look other than this website when I come into trouble with my PHP.
What I'm trying to do here is use pre-designated IDs to call particular movies from a database. But all I get is an 'Invalid argument supplied for foreach()' message on the second and third foreach's below.
Here's my code in the head:
//Custom lists of movies to bring in
//New Releases list
$films_new_releases = array(40805, 46705, 41630, 44564, 39451, 20352, 43933, 49009, 49797, 42194);
//Most Popular list
$films_most_popular = array(27205, 16290, 10138, 41733, 37799, 18785, 19995, 17654, 10140, 12162);
//Get information from address bar
$list = $_GET['l'];
if ($list == 'new releases') {
$list_chosen = $films_new_releases;
}
elseif ($list == 'most popular') {
$list_chosen = $films_most_popular;
}
else {
$list_chosen = $films_new_releases;
}
And in amongst the body:
// Loop through each film returned
foreach ($list_chosen as $list_chosen_film) {
$films_result = $tmdb->getMovie($list_chosen_film);
$film = json_decode($films_result);
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'poster') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . $film->name . '" />
<div class="view-films-film-snippet">
<h2>' . $film->name . '</h2>';
if ($film->certification != null) {
echo '<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />';
}
echo ' <h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($film->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($film->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
}
// End films
}
The little testing I've done is checking what $list_chosen, $list_chosen_film, $films_result and $film actually contain by printing them at the bottom of the page.
$list_chosen shows - Array, $list_chosen_film shows - 42194, $films_result shows the entire JSON string, $film shows - Array.
Try adding:
print_r($film->backdrop);
before the second foreach() loop. Before the error message it won't be an array or it will contain zero elements (not allowed). If you also add:
echo $films_result;
you will be able to debug it and fully understand what is wrong. If not, post the whole output in your question.
This happens, because - as error displayed by PHP informed you - you have provided wrong parameter to foreach loop, probably null or some other value. Make sure you are providing array to foreach.
Also, every time you use foreach, do it like that:
if (count($some_list) > 0) {
foreach ($some_list as $list_item) {
// code for each item on the list
}
} else {
// code when there is nothing on the list
}
This will ensure you will not see errors just because there is nothing on the list.
EDIT:
On the documentation page you can find some tip how to avoid such errors if the collection you are trying to iterate through is empty. Just cast the collection to array type:
foreach ((array) $some_list as $list_item) {
// code for each item on the list
}
Can you provide a dump of $film? The error is telling you that you are pointing to an object that cannot be iterated through (most likely null).

Dynamic Background images advice

I am creating a site where users can upload there own background images, after upload they see each background they uploaded in a menu represented by a number, clicking on the number will in theory load in the new background, however I have noticed that does this calls in the view again as well (the view is already loaded from another function, is there a ways I can pass the data to the view without loading the view, can I do it with ajax? if so how?
My code currently
public function set_background() {
$this->load->model('image_model');
if($query = $this->image_model->get_background_by_id($this->uri->segments[3])) {
if($query) {
$data['new_background'] = $query;
}
}
$this->load->view('template/background-select', $data);
}
My Model:
public function get_background_by_id($background_id) {
$this->db->select('background_name');
$this->db->from('background');
$this->db->where('background_id', $background_id);
$query = $this->db->get();
return $query->result_array();
}
My View
<div id="background-select">
<?php
$count = 0;
if(isset($special)) {
foreach ($special as $row) {
$count ++;
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
if($count == 1) {
$background = $row['background_name'];
}
}
}
if(isset($generic)) {
foreach ($generic as $row) {
$count ++;
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
if($count == 1) {
$background = $row['background_name'];
}
}
}
if(isset($user_background)) {
foreach ($user_background as $row) {
$count ++;
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
if($count == 1) {
$background = $row['background_name'];
}
}
}
?>
</div>
<div id="wrapper" style=<?php echo"background:url(/media/uploads/backgrounds/".$background.");";?>>
The view gets loaded in originally here
public function index() {
// $this->output->enable_profiler(TRUE);
$data = array();
if($query = $this->category_model->get_all_online()) {
$data['main_menu'] = $query;
}
$this->load->model('image_model');
/*
* Sort out the users backgrounds, basically do a check to see if there is a 'special' background
* if there is not a 'special' background then IF the user is logged in and has a background of there
* own show that one, if not show a generic one, if they are not logged in show a bang one
*/
$image = array();
if ($query = $this->image_model->get_special_backgrounds()) {
$image['special'] = $query;
} elseif(!isset($image['special']) && !isset($this->session->userdata['user_id'])) {
if($query = $this->image_model->get_bang_background()) {
$image['generic'] = $query;
}
}
if(isset($this->session->userdata['user_id'])) {
if($query = $this->image_model->get_user_backgrounds($this->session->userdata['user_id'])) {
$image['user_background'] = $query;
}
}
$data = array_merge($data, $image);
$this->load->view('home/main_page.php', array_merge($data, $image));
}
Hope some can help thanks
This may be too much 'out of the box' and not faithful enough to your code to be useful, but here goes:
Given the description of what the code is supposed to do, you could always have your PHP output the list of background images into a JavaScript snippet on the view (To pseudocode very roughly: <script><?php echo phpArrayToJavaScriptArray($images, $varName); ?></script>), then have javascript dynamically create your list of background-changing links client-side and each click just change the background image with JavaScript (<a href="javascript:changeBackgroundImage('url')"> setting document.getElementById('wrapper')'s background image).
No Ajax necessary.
With that concept in mind, the simplest adjustment to your code I can concot in a hurry is this:
Instead of passing the IDs to the view, pass the URLs to the view (you'd have to adjust your querying accordingly, of course), and change:
"<a
class='background_btn'
href='index.php/home/set_background/" . $row['background_id'] . "'>"
. $count
. "</a>"
to something like
"<a
class='background_btn'
href=\"javascript:changeBackgroundImage('"
. htmlspecialchars($row['background_url'], ENT_QUOTES, 'utf-8')
. "')\">"
. $count
. "</a>"
The JavaScript function would be something like this:
<script language="javascript">
function changeBackgroundImage(url) {
var wrapper = document.getElementById('wrapper');
wrapper.style = "background-image:url(" + url + ")";
}
</script>
Mind, the lot of that is still pseudocode, I doubt it'll run out of the box, my JS is very rusty, and this is meant to be an idea-share more than an outright fix. :) But I hope that it'll help you tackle your issue!
Is that kind of approach feasible for you?

Categories