Image not being displayed when received via AJAX - javascript

I have an image in my mysql DB, in type longblob. I have an ajax call that requests the image and on success, changes my html image src to be the received image. My ajax post response is the image name (114046.png) but it will trigger the ajax error section, not success. Can someone look through my code and tell me where im going wrong?
Saving image in DB
public function UploadImage($imageData) {
global $dbCon;
$imgFile = $imageData['file']['name'];
$imgSize = $imageData['file']['size'];
if(empty($imgFile)){
error_log("image file empty");
}
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
if(!in_array($imgExt, $valid_extensions)) {
error_log("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
}
// Check file size '5MB'
if($imgSize > 5000000) {
error_log("Sorry, your file is too large.");
}
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
$sql = 'UPDATE userinfo SET image=(:image) WHERE username="'.$this->currentUsername.'"';
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':image', $userpic);
$stmt->execute();
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
//image uploaded
}
}
Getting the image from the DB
public function GetImage() {
global $dbCon;
$stmt = $dbCon->query("SELECT image FROM userinfo WHERE username='".$this->currentUsername."'");
$fetchResult = $stmt->fetch();
$data = $fetchResult["image"];
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
$this->LatestUpdate = "Get Image";
$this->image = $data;
}
}
public function GetTheImage() {
return $this->image;
}
Responding to ajax
if($this->model->LatestUpdate() == "Get Image") {
header("Content-type: image/png");
echo $this->model->GetTheImage();
exit();
}
Ajax call (Set the HTML image to the received image)
window.onload = SetImage;
function SetImage() {
data = "action=" + "getImage";
$.ajax({
url: '../index.php', // point to server-side PHP script
dataType: 'image/png', // what to expect back from the PHP script, if anything
data: data,
type: 'post',
success: function(image) {
console.log("success");
$("#profileImage").attr("src", image);
}, error: function(xhr, status, error) {
alert("Error" + xhr.responseText);
}
});
}

Related

How set background img from MySQL database in 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>

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');
}
}

AJAX jQuery Avatar Uploading

I've been trying to find a very basic AJAX jQuery Avatar Uploading that I can use for my "settings" page so users can upload an avatar and unfortunately I can't find any.
This is my "function" so far for uploading the avatar
function uploadAvatar(){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html("Logging in, please wait....");
dataString = $('#avatarForm').serialize();
var postURL = $('#avatarForm').attr("action");
$.ajax({
type: "POST",
url: site_url+"/libraries/ajax/image-upload.php",
data:dataString,
dataType:"json",
cache:false,
success:function(data){
if(data.err){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.err);
}else if(data.msg){
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
var delay = 2000;
window.setTimeout(function(){
location.reload(true);
}, delay);
}
}
});
return false;
};
For my HTML/Input is this.
<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit" id="submit-btn" onClick="uploadAvatar();" value="Upload" />
And finally this is my PHP code (I have nothing here)
$thumb_square_size = 200;
$max_image_size = 500;
$thumb_prefix = "thumb_";
$destination_folder = './data/avatars/';
$jpeg_quality = 90; //jpeg quality
$return_json = array();
if($err==""){ $return_json['msg'] = $msg; }
else{ $return_json['err'] = $err; }
echo json_encode($return_json);
exit;
So how do I start this really. I just don't know where to start, I don't know exactly what to do.
Bulletproof is a nice PHP image upload class which encorporates common security concerns and practices, so we will use it here as it also makes the whole process much simpler and cleaner. You will want to read the approved answer on this question here (https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form) to better understand the risks of accepting file uploads from users.
The PHP below is really basic and really only handle the image upload. You would want to save the path or the file name that was generated in a database or in some kind of storage if the image is uploaded successfully.
You may also want to change the directory in which the image is uploaded to. To do this, change the parameter for ->uploadDir("uploads") to some other relative or absolute path. This value "uploads" will upload the image to the libraries/ajax/uploads directory. If the directory does not exist, bulletproof will first create it.
You will need to download bulletproof (https://github.com/samayo/bulletproof) and make sure to upload or place it in libraries/bulletproof/. When you download the class from github it will be in a ZIP archive. Extract the zip archive and rename bulletproof-master director to just plain bulletproof. Place that directory in the libraries directory.
HTML
<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
</form>
JS
$('#avatar_form').submit(function( event ){
event.preventDefault();
var formData = new FormData($(this)[0]); //use form data, not serialized string
$('#avatarDialog').fadeIn();
$('#avatarDialog').html("Logging in, please wait....");
$.ajax({
type: "POST",
url: site_url + "/libraries/ajax/image-upload.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data){
if(data.code != 200){ //response code other than 200, error
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
} else { // response code was 200, everything is OK
$('#avatarDialog').fadeIn();
$('#avatarDialog').html(data.msg);
var delay = 2000;
window.setTimeout(function(){
location.reload(true);
}, delay);
}
}
});
return false;
});
PHP
//bulletproof image uploads
//https://github.com/samayo/bulletproof
require_once('../bulletproof/src/bulletproof.php');
$bulletproof = new ImageUploader\BulletProof;
//our default json response
$json = array('code' => 200, 'msg' => "Avatar uploaded!");
//if a file was submitted
if($_FILES)
{
try
{
//rename the file to some unique
//md5 hash value of current timestamp and a random number between 0 & 1000
$filename = md5(time() . rand(0, 1000));
$result = $bulletproof->fileTypes(["png", "jpeg"]) //only accept png/jpeg image types
->uploadDir("uploads") //create folder 'pics' if it does not exist.
->limitSize(["min" => 1000, "max" => 300000]) //limit image size (in bytes) .01mb - 3.0mb
->shrink(["height" => 96, "width" => 96]) //limit image dimensions
->upload($_FILES['image_file'], $filename); // upload to folder 'pics'
//maybe save the filename and other information to a database at this point
//print the json output
print_r(json_encode($json));
}
catch(Exception $e)
{
$json['code'] = 500;
$json['msg'] = $e->getMessage();
print_r(json_encode($json));
}
}
else
{
//no file was submitted
//send back a 500 error code and a error message
$json['code'] = 500;
$json['msg'] = "You must select a file";
print_r(json_encode($json));
}
Bulletproof will throw an exception if the image does not pass the validation tests. We catch the exception in the try catch block and return the error message back to the JavaScript in the JSON return.
The rest of the code is commented pretty well from the Bulletproof github page etc, but comment if anything is not clear.

How can I return the path of a screenshot capture to a function and return via JSON to javascript?

I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);

Call a certain URL on HTML5 upload

Alright, So I have this script that uploads a file on drag and drop from the browser using HTML5.
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
// The name of the $_FILES entry:
paramname:'pic',
maxfiles: 50,
maxfilesize: 50,
url: 'post_file.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
// response is the JSON object that post_file.php returns
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! Please select 20 at most! (configurable)');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 10mb (configurable).');
break;
default:
break;
}
},
//// Called before each upload is started
// beforeEach: function(file){
// if(!file.type.match(/^image\//)){
// alert('Only images are allowed!');
//
// // Returning false will cause the
// // file to be rejected
// return false;
// }
// },
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
// e.target.result holds the DataURL which
// can be used as a source of the image:
image.attr('src',e.target.result);
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's $.data():
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
It runs on with the following post_file.php
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
//$allowed_ext = array('jpg','jpeg','png','gif','doc','docx','pdf','xls','xlsx','pptx','ppt','rtf','txt','mp4','css','rar','zip','exe','mp3','wav');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
//if(!in_array(get_extension($pic['name']),$allowed_ext)){
// exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
//}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
Now the problem is I have a certain JSON url that when I open it sends a text message to a certain number. I'm trying to append that URL somewhere in the script so that it runs that url everytime an upload is made.
Any ideas?
$URL = "http://www.api.com/api.php?data=mydata";
$data = file_get_contents($URL);
This solves it.

Categories

Resources