How set background img from MySQL database in javascript - javascript

I am using codelgniter, vanilla javascript , ajex, css, MySQL only
I want set background of image which store in mySQL database
The following code is working very well & not get error but problem is that how can I set background of image storage in database
Note the image is must be get using ajex ( xhr request respond )
The javascript create following css dynamically
.demo0::before {
Background: URL ("path");
}
.demo1::before {
Background: URL ("path");
}
.demo2::before {
Background: URL ("path");
}
And so on
I have following vanilla javascript
background_img=www.Demo.jpg; //temporary set
d_no=0;
Style0 = document.getElementByITagName("style")[0];
Style0.type="text/css";
Data=style0.innerHTML;
style0.innerHTML = data + "demo" d_no+"before { background: url("+ background_img +" );}";
d_no=d_no+1;

it is simple but tricky you need to make controller model of getting img src/url value in css or javascript or html url or src is may be path or image value
use following code
controller
<?php
class cover_img extends CI_Controller
{
public function index()
{
$getRequestData=stripslashes(file_get_contents("php://input"));
$datas=json_decode($getRequestData,true);
$this->load->model("cover_img_model","cim");
$this->cim->get_cover_img($datas["f_id"]);
}
}
?>
model
<?php
class cover_img_model extends CI_Model
{
function get_cover_img($username)
{
// echo $username;
$data=$this->db->query("select cover from user_detail where user_name='$username'");
foreach ($data->result_array() as $row)
{
echo "data:image/jpg;charset=utf8;base64,";
echo base64_encode($row['cover']);
}
}
}
?>
vanilla javascript
style0=document.getElementsByTagName("style")[0];
style0.type="text/css";
ccs_data=style0.innerHTML+"\n \n";
xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/CI-social-media/index.php/cover_img", false);
obj = {"f_id":f_id}; // f_id is primary key field value for get the img using where condition in mysql change this f_id dynamically for getting different img
// alert(f_id);
data = JSON.stringify(obj);
xhr.onload = () => {
if (xhr.status == 200) {
if (xhr.response) {
style0.innerHTML = ccs_data +"\t "+ ".demo" + d_no + "::before{ \n\t\t background: url('"+xhr.responseText+"'); \n\t} ";
// alert(xhr.responseText);
}
else {
alert("something want wrong try agin later")
}
}
else {
alert("Something Want Wrong Try agin");
}
}
xhr.send(data);
document.getElementsByTagName('head')[0].appendChild(style0);
d_no=d_no+1;

If you get binary image from server:
<script>
fetch("/image") // url of binary image response
.then((response) => response.blob())
.then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
document.querySelector('#body') // element selector, which has background
.style.backgroundImage = `url(${objectURL})`
});
</script>
If you have static image
<script>
fetch("/get-image.php") // url of php script, which returns url to static image
.then((response) => response.text())
.then((src) => {
document.querySelector('#body') // element selector, which has background
.style.backgroundImage = `url(${src})`
});
</script>

Related

If image url not exist on server replace url with other (multiple time)

I made lastposter avatar for my forum system.
What i want : when user avatar img not exist change file type multiple time. Such example; if user_{userid}_avatar.png not exist change url to user_{user_id}_avatar.jpg and again it's not exist change to user_{userid}_avatar.gif and etc.({user_id} coming as php variable that's no matter).
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
You can do something like this:
Javascript:
var img_types = ['jpeg', 'gif', 'png'];
var avatar = '';
for(var i=0;i<img_types.length();i++) {
avatar = new File("/path/to/avtar." + img_types[i]);
// See if the file exists
if(avatar.exists()){
break;
}
}
PHP:
<?php
// put allowed image types in this array
$img_types = ['jpeg', 'gif', 'png'];
// avatar URL will be stored in here
$avatar = '';
// loop over the image_types array
foreach($img_types as $img_type) {
$avatar = '/path/to/user_{userid}_avatar.' . $img_type;
// check if the files exists
if(file_exists($avatar)) {
// exit the foreach loop, because we found the image
break;
}
}
?>
You can use a function like this.
function image_exists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}

PDF file not downloading or being saved to folder

I posted about this issue not that long ago, and I thought I had figured it out but nothing is happening.
Issue: I am trying to generate a PDF file that captures the signature of a client. Essentially they type in their name in a box and that name gets displayed in the pdf.php file along with all the other information(e.g. date, terms & conditions etc..).
I created a class that extends from FPDF and though JavaScript I am sending the name that gets filled and it gets processed through that pdf.php file and should return a "signed" pdf file.
However my pdf file is not downloading, saving or any of the options (I, D, F, S).
Below is a snippet of that section in my code.
pdf.php
$tempDir = "C:/PHP/temp/";
$thisaction = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
$answers = filter_input(INPUT_POST, 'encFormData');
$decFD = json_decode($answers);
$pdf = new WaiverFPDF();
// Pull values from array
$returnVals = array();
$returnVals['result'];
$returnVals['html'] = '';
$returnVals['errorMsg'] = '';
//the name of the person who signed the waiver
$name = $decFD->signWaiver;
$today = date('m/d/Y');
if($thisaction == 'waiverName'){
// Generate a new PDF
$pdf = new WaiverFPDF();
$pdf->AddPage()
$pdfFile = "Waiver". $name . ".pdf";
....
// Output form
$pdf->Write(8, 'I HEREBY ASSUME ALL OF THE RISKS...');
// Line Break
$pdf-> all other info...
$outFile = $tempDir . $pdfFile;
//output pdf
$pdf->Output('D', $pdfFile);
$returnVals['result'] = true;
}
else{
$returnVals['errorMsg'] = "There was an error in waiver.php";
$returnVals['result'] = false;
}
echo json_encode($returnVals);
?>
.js file (JSON)
function sendWaiver(){
var formHash = new Hash();
formHash.signWaiver = $('signWaiver').get('value');
console.log ("name being encoded");
waiverNameRequest.setOptions({
data : {
'encFormData' : JSON.encode(formHash)
}
}).send();
return true;
}
waiverNameRequest = new Request.JSON({
method : 'post',
async : false,
url : 'pdf.php',
data : {
'action' : 'waiverName',
'encFormData' : ''
},
onRequest : function() {
// $('messageDiv').set('html', 'processing...');
console.log("waiver onRequest");
},
onSuccess : function(response) {
$('messageDiv').set('html', 'PDF has been downloaded');
if (response.result == true) {
console.log('OnSuccess PDF created');
} else {
$('messageDiv').set('html', response.errorMsg);
console.log('PDF error');
}
}
});
I know my error handling is very simple, but all I am getting is success messages, but no generated pdf file... I'm not sure what i am doing wrong. I also made sure the file (when i save to a file) is writable.
class_WaiverFPDF.php
class WaiverFPDF extends FPDF
{
// Page header
function Header()
{
// Arial bold 15
$this->SetFont('Arial','B',12);
// Position XY X=20, Y=25
$this->SetXY(15,25);
// Title
$this->Cell(179,10, 'Accident Waiver ','B','C');
// Line break
$this->Ln(11);
}
// Page footer
function Footer()
{
// Position from bottom
$this->SetY(-21);
// Arial italic 8
$this->SetFont('Arial','I',8);
$this->Ln();
// Current date
$this->SetFont('Arial','I',8);
// $this->Cell(179,10,$today,0,1,'R',false);
// $today= date('m/d/Y');
$this->Cell(115,10,' Participant Name',0,0,'C');
$this->Cell(150,10,'Date',0,'C',false);
// Page number
//$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}

How can I do update with using same id but different content?

Currently, I working on form that got an input for image file. After browse image then upload it I will get the id for the image. Here is my code for POST.
$("#smallpicture_id").change(function () {
displayAndShowImage(this,'#smallimg','#smallimg');
});
$("#largepicture_id").change(function () {
displayAndShowImage(this,'#largeimg','#largeimg');
});
function displayAndShowImage(input,targetHtmlElementName) {
if (input.files && input.files[0]) {
var files = input.files;
var reader = new FileReader();
reader.onload = function (e) {
$(targetHtmlElementName).attr('src', 'images/uploading.gif');
var formData = new FormData();
formData.append('userfile',files[0],files[0].name);
createImage(
config,
formData,
{
onSuccess : function(data) {
$(targetHtmlElementName).attr('src', e.target.result);
$.cookie(input.id, data);
console.log("Image has been save - Received ID: " + data + " saved in the cookie " + input.id);
},
onError : function(jqXHR, status) {
$(targetHtmlElementName).attr('src', 'images/img-error.png');
console.log("ERROR " + jqXHR.responseText + "\r\nstatus = " + status);
}
}
);
}
reader.readAsDataURL(files[0]);
}
}
Ajax
function createImage(cfg,formData,callbacks) {
var xhr = new XMLHttpRequest();
xhr.open('POST', cfg.url + "/image/", true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
callbacks.onSuccess(xhr.responseText.trim());
} else {
callbacks.onError(xhr);
}
};
xhr.send(formData);
}
My question is how can I update / delete for my image with using the same id that given to the image. I already can do POST and GET but I still don't get any idea how to update and delete.
You can append two string in FormData query identifier and ID (only in case of update & delete), like
formData.append('queryType', 'DELETE')
formData.append('imageID', input.id)
On server side code (where you have added code for saving new Image) you have to add condintion like this
<?php
$identifier=$_POST['queryType'];
if($identifier=="NEW") {
//save file with new ID and return ID
} elseif ($identifier=="UPDATE")
//update Image Data ($_FILE) with ID appended in formdata
} elseif ($identifier=="DELETE")
//Delete existing image at ID specified
}
?>
hope this may help.
You can give your elements specific classname for each upload process, which have same id, then run displayAndShowImage function for only elements has "update-this" classname.
$("#smallpicture_id").change(function () {
$(this).addClass("update-this"); // add update-this class
$(".update-this").not($(this)).removeClass("update-this"); // remove all update-this classnames from all other ones
// then run your function for only element which has update-this classname
displayAndShowImage(this,'.update-this');
});

POSTing data serverside AND execute javascript code on submitting a form

My goal is to upload some images to a server and provide them with a description.
On clicking an upload button, this is what I want to happen:
1) a javascript function dynamically adds a form to get a description
of the images.
2) on submitting the form:
a) the description entered in the form must be available $_POST['description'] at server side.
b) the images are sent to the server using an XMLHttpRequest
In the code I wrote the description is not available $_POST['description'].
When i remove the check if(!isset($_POST['description'])), the imagefiles are perfectly uploaded.
This is my code:
javascript code
upload.onclick = uploadPrompt;
// dynamically add a form
function uploadPrompt () {
// fileQueue is an array containing all images that need to be uploaded
if (fileQueue.length < 1) {
alert("There are no images available for uploading.");
} else {
var inputDescription = document.createElement("input");
inputDescription.className = "promptInput";
inputDescription.type = "text";
inputDescription.name = "description";
var inputButton = document.createElement("button");
inputButton.id = "promptInputButton";
inputButton.type = "submit";
inputButton.innerHTML = "Start uploading";
var promptForm = document.createElement("form");
promptForm.method = "post";
promptForm.action = "upload.php";
promptForm.onsubmit = uploadQueue;
promptForm.id = "promptForm";
promptForm.appendChild(inputDescription);
promptForm.appendChild(inputButton);
document.body.appendChild(promptForm);
}
}
function uploadQueue(ev) {
ev.preventDefault();
elementToBeRemoved = document.getElementById("promptForm");
elementToBeRemoved.parentElement.removeChild(elementToBeRemoved);
while (fileQueue.length > 0) {
var item = fileQueue.pop();
// item.file is the actual image data
uploadFile(item.file);
}
}
function uploadFile (file) {
if (file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('image',file);
xhr.upload.addEventListener("error", function (ev) {
console.log(ev);
}, false);
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(fd);
}
}
php code upload.php
<?php
session_start();
if (!isset($_POST['description'])) {
echo "upload:fail\n";
echo "message:No scene was specified";
exit();
}
if (isset($_FILES['image'])) {
if(!move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $_POST['description'] . "/" . $_FILES['image']['name'])) {
echo "upload:fail\n";
}
else {
echo "upload:succes\n";
}
exit();
}
exit();
?>
I'd really advise against creating your own asynchronous file upload functionality when there is a plethora of developers who have already programmed the same thing better. Check out these options:
Blueimp's jQuery file uploader
Uploadifive (Uploadify's HTML5 implementation)
I've used these two before and they work very well. For BlueImp, you can use this option to send additional form data:
$('#fileupload').fileupload({
formData: $('.some_form').serialize()
});
The above captures a form and serializes its inputs. Alternatively, you can populate an array or object using specific values (i.e. from specific elements in your DOM):
var array = new Array();
$('.description').each(function() {
array[this.id] = this.value;
});
You'd use IDs to link your files and descriptions.

How can I iterate through all elements of local (server-side) folder?

Basically, I have a very simple website where the root directory looks like:
/images/
index.html
stuff.js
I want some way to recursively iterate through every file in the /images/ directory and display them in order in a section of my website. So for example, if /images/ contained:
images/a/a.png
images/b.png
images/c.jpg
....
then somewhere in index.html would contain:
<img src="images/a/a.png" />
<img src="images/b.png" />
<img src="images/c.jpg" />
....
My first idea was to do this using the document.write() function in stuff.js, but I couldn't find a good way to iterate through the local file directory in Javascript. I saw something about AJAX, but all of those examples involved editing an existing file, which I obviously don't want to do.
My current solution is just to manual create an array of strings containing all of the files in /images/, but doing this makes me think "There's got to be a better way!"
Let me know if I've been unclear.
Thanks!
Perhaps the best way to do this is to use a server-sided language to do it for you, and to use an asynchronous Javascript request to display the data.
This sample uses PHP to list all the files in a specified directory, and an xmlhttprequest to load this output and convert the results into image tags:
getimages.php:
<?php
//The directory (relative to this file) that holds the images
$dir = "Images";
//This array will hold all the image addresses
$result = array();
//Get all the files in the specified directory
$files = scandir($dir);
foreach($files as $file) {
switch(ltrim(strstr($file, '.'), '.')) {
//If the file is an image, add it to the array
case "jpg": case "jpeg":case "png":case "gif":
$result[] = $dir . "/" . $file;
}
}
//Convert the array into JSON
$resultJson = json_encode($result);
//Output the JSON object
//This is what the AJAX request will see
echo($resultJson);
?>
index.html (same directory as getimages.php):
<!DOCTYPE html>
<html>
<head>
<title>Image List Thing</title>
</head>
<body>
<div id="images"></div>
<input type="button" onclick="callForImages()" value="Load" />
<script>
//The div element that will contain the images
var imageContainer = document.getElementById("images");
//Makes an asynch request, loading the getimages.php file
function callForImages() {
//Create the request object
var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
//When it loads,
httpReq.onload = function() {
//Convert the result back into JSON
var result = JSON.parse(httpReq.responseText);
//Show the images
loadImages(result);
}
//Request the page
try {
httpReq.open("GET", "getimages.php", true);
httpReq.send(null);
} catch(e) {
console.log(e);
}
}
//Generates the images and sticks them in the container
function loadImages(images) {
//For each image,
for(var i = 0; i < images.length; i++) {
//Make a new image element, setting the source to the source in the array
var newImage = document.createElement("img");
newImage.setAttribute("src", images[i]);
//Add it to the container
imageContainer.appendChild(newImage);
}
}
</script>
</body>
</html>
Note that this is only an example. You'll probably want to make sure that the AJAX call is successful, and that the JSON conversion works both in the server code and on the client.
I stumbled on this article, as I was looking for the same thing, how to iterate through a list of files in a "Resources" folder, and display a webpage with clickable shortcuts to each of them.
Here's a clip of the webpage I ended up with:
Here's how I did it.
I added a very simple ASP.Net service, to iterate through the files in this folder...
List<OneResourceFile> listOfFilenames = new List<OneResourceFile>();
string Icon = "";
string localFolder = Server.MapPath("../Resources");
string[] fileEntries = Directory.GetFiles(localFolder);
foreach (string fileName in fileEntries)
{
string filename = System.IO.Path.GetFileName(fileName);
switch (Path.GetExtension(filename).ToLower())
{
case ".pptx":
case ".ppt":
Icon = "cssPowerPoint";
break;
case ".doc":
case ".docx":
Icon = "cssWord";
break;
case ".xlsx":
case ".xlsm":
case ".xls":
Icon = "cssExcel";
break;
default:
Icon = "cssUnknown";
break;
}
OneResourceFile oneFile = new OneResourceFile()
{
Filename = filename,
IconClass = Icon,
URL = "../Resources/" + filename
};
listOfFilenames.Add(oneFile);
}
string JSON = JsonConvert.SerializeObject(listOfFilenames);
return JSON;
..which built up a List of OneResouceFile records, each with a Filename, a CSS Class to apply to that shortcut (which would give it, say, an Excel icon, a PDF icon, etc) and a full URL of the item.
public class OneResourceFile
{
public string Filename { get; set; }
public string IconClass { get; set; }
public string URL { get; set; }
}
..and which returned a JSON set of results like this...
[
{
Filename: "Mikes Presentation.pptx",
IconClass: "cssPowerPoint",
URL: "~/Resources/Mikes Presentation.pptx"
},
{
Filename: "Mikes Accounts.xlsx",
IconClass: "cssExcel",
URL: "~/Resources/Mikes Accounts.xlsx""
}
]
Then, I just got some JQuery to call this web service, and create a a href for each item in the results:
<script type="text/javascript">
var URL = "/GetListOfResourceFiles.aspx"; // This is my web service
$.ajax({
url: URL,
type: 'GET',
cache: false,
dataType: "json",
success: function (JSON) {
// We've successfully loaded our JSON data
$.each(JSON.Results, function (inx) {
// Create one <a href> per JSON record, and append it to our list.
var thelink = $('<a>', {
text: this.Filename,
title: this.Filename,
href: this.URL,
class: this.IconClass
}).appendTo('#ListOfResources');
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("$.ajax error: " + xhr.status + " " + thrownError);
}
});
</script>
<p id="ListOfResources">
All you need then is to add some CSS styling for cssPowerPoint, cssExcel, etc, to give the a hrefs a relevant icon, for example:
.cssPowerpoint
{
vertical-align: top;
text-align: center;
background-repeat: no-repeat;
background-position: center 5px;
background-image: url(/Images/Icons/icnPowerPoint.png);
width: 100px;
height: 60px;
padding-top: 60px;
text-decoration: none;
display:inline-block;
color: #666;
margin-left: 20px;
}
And that's it. Cool, hey ?

Categories

Resources