I have this code where you click a button to upload multiple files. When user have select the images, it will automatically upload the files, then preview show the uploaded files. But this error appeared when preview list appear (sometimes few images loaded successfully).
I'm using Ajax and Form Data to send the images, return an array of successful uploaded image's names, and append preview div when completed. The image upload is working fine, so here's my code on the Ajax success return:
$.ajax({
url: 'process.php',
type: 'POST',
data: form_data,
dataType: 'json',
async: false,
success: function (data) {
if(data){
$.each(data, function(index, value) {
var img = "'../content/"+brand+"/"+category+"/"+value+".png'";
$('<li id="product-'+value+'" class="product item-flex-2"><div class="list-menu border-bottom"><i id="delete-product-'+value+'" class="fa fa-remove pointer color-red-hover"></i></div><div id="img-'+value+'" class="img-wrapper" style="background-image:url('+img+')"></div></li>').insertBefore($('#product-new'));
$('#upload-product').val();
});
} else {
alert('Upload Failed.');
}
},
cache: false,
contentType: false,
processData: false
});
Here's the code on PHP file that process upload file:
$product = array();
$brand = $_POST['brand-owner'];
$category = $_POST['category'];
$res_dir = '../content/'.$brand.'/'.$category.'/';
$count = count($_FILES['upload-product']['name']);
$last_file = count(array_diff(scandir($res_dir), array('..', '.', 'index.html')));
$html_dir = $res_dir.'index.html';
for ($i = 0; $i < $count; $i++) {
$last_file++;
$tmp_file_name = $_FILES['upload-product']['tmp_name'][$i];
$new_name = $res_dir.str_pad(($last_file),3,0,STR_PAD_LEFT).'.png';
$create_png = imgToPng($tmp_file_name);
if(imagepng($create_png, $new_name)){
array_push($product,str_pad($last_file,3,0,STR_PAD_LEFT));
}
}
generateHTML($html_dir, 'product', $brand, $category);
echo json_encode($product);
Here's imgToPng function code (if needed):
function imgToPng($tmp_file_name) {
$create_png = imagecreatefromstring(file_get_contents($tmp_file_name));
imageAlphaBlending($create_png, true);
imageSaveAlpha($create_png, true);
return $create_png;
}
I also have preview menu with similar code as above, and the error also appear there. I've tried CTRL + F5 to force refresh but it only works after few attempts. I've searching look around but most is about Firefox's Bug (i'm on 48.0.2) or the error is on img tag. I have another html page that use img tag and show no error, but i need to use div on this page.
Thank you...
Update : It looks like the image is corrupt after converted to png. I tried with original extension and the images load correctly. So either my code is incorrect or something wrong with PHP function.
Related
code at controller side is given below
try {
$this->load->library('m_pdf');
$querytype = "advance_search";
$showdata = [];
$pdfFilePath = utf8_decode("download_pdf.pdf");
ob_start();
$body= $this->load->view('result/pdf_generation', $this->common_advance_search($querytype),false); //here i am loading view for pdf
$this->m_pdf->pdf->WriteHTML($body);
$this->m_pdf->pdf->Output(FCPATH.$pdfFilePath,'F');// till here i can see the data in view
$result = ob_get_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/pdf;base64,".base64_encode($result)
);
die(json_encode($response));
}
catch(\Mpdf\MpdfException $e) {
echo $e->getMessage();
}
Ajax Code
$.ajax({
url : "<?php echo base_url(); ?>"+scr,
method:"POST",
data:formData,
contentType: false,
cache: false,
processData:false,
dataType:'json'
}).done(function(data){ // here i am able to download the pdf in the browser
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","file."+ext);
$a[0].click();
$a.remove();
});
result is given below
check result (screen shot added here)
with this code, it is giving me a currpted PDF file, i am able to get data and 'Export as pdf'. I have checked whether it is passing data from view, and yes it is doing so. But don't know what is the matter . I is printing everything outside it is working fine, Can anyone please let me know what should I do?
I have an AJAX call to the create_pdf.php page:
$('body').on('click', '.PrintButtonWithClass', function (event) {
var1 = $('#id1').val();
var2 = $('#id2').val();
dataString='var1='+var1+'&var2='+var2+'&pdf_name=PdfName&pdf_creator=myname';
$.ajax({
type: 'post',
url: '/path/to/createpdf/file/create_pdf.php',
data: dataString,
success: function (data) {
alert('success');
}
});
});
In create_pdf.php I tried to use this line to download the file:
$pdf->Output(str_replace(' ','_',utf8_decode($_POST['pdf_name'])).'.pdf', 'D');
I tried also the FD and I parameters with no success, the file does not get downloaded.
How can I force downloading the file created without saving it to the webserver and without redirecting user to any other page? I want him to stay on the same page, and that the browser pops up a (download or preview dialog box) for the PDF. Is there any way to do it?
EDIT : create_pdf.php is Waiting for POST variables. and uses them to create the HMTL for the pdf.
You can try to submit the form to a new window( like a popup ):
<form method="post" id="myform" action="your_url">
<input name="param1">
</form>
And in javascript
// create popup window
var wind = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');
// submit form to popup window
$("#myform").attr("target", "__foo");
Do not forget to send content-type header from php:
header("Content-Type", "application/pdf");
Edit:
Browsers should display your pdf content and also show download or print options.
The code is not tested but I think it would do what you requested;
I found a work-around for my problem.
I did an AJAX call inside another AJAX call.
the first AJAX call creates the file on webServer and opens the file in a new Window.
In his success parameter I do the following:
The second AJAX call that deletes the file from Server.
$.ajax({
type: 'post',
url: '/path/to/create_pdf.php',
data: dataString,
success: function (data) {
window.open(
data,
'_blank' // <- This is what makes it open in a new window.
);
window.setTimeout(function () {
dataString2 = 'Downloaded=true';
$.ajax({
type: 'post',
url: '/path/to/create_pdf.php',
data: dataString2,
success: function (data) { alert(data); }, // handler if second request succeeds
});
}, 5000);
},
});
Using this answer to my similar request : send a csv file from php to browser
I needed to (1) get and display a pdf in another window; and
(2) get a CSV file and prompt for saving.
I have 2 simple buttons on the page (http://potoococha.net/) for each. Here is the code:
function getCSVText(evt) {
if (currentChecklistCountry) {
var form = $('<form method="post" action="../php/sendCSV.php?country=' + currentChecklistCountry + '"></form>');
$('body').append(form);
form.submit();
form.remove();
}
else checklistCountryButton.classList.add("needsAttention");
}
function openChecklistPage() {
if (!currentChecklistCountry) {
checklistCountryButton.innerHTML = "Select Country";
checklistCountryButton.classList.add("needsAttention");
return;
}
if (gNumDays == undefined) gNumDays = 12;
vars = "?country=" + currentChecklistCountry;
vars += "&num_days=" + gNumDays;
vars += "&line_nos=" + lineNumbers.checked;
vars += "&left_check=" + leftCheck.checked;
vars += "&endemics=" + showEndemics.checked;
vars += "&sci_names=" + !sciNames.checked;
vars += "&italics=" + !italics.checked;
window.open( '../php/makePDF.php' + vars, '_blank' );
}
So the getCSVText() methods downloads a file using a temporary form appended and then immediately removed, and openChecklistPage() successfully opens another browser window with a pdf file. The pdf file is never saved on the server. The CSV file is already stored there and just retrieved. Perhaps you can modify the code for your purposes.
please help to resolve the following issues:
There is a page which loads the image.
50 pictures.
How to make, that images would be displayed gradually (example google photo)?
$(document).ready(function(){
$.ajax({
type: 'POST',
url: document.location.href,
dataType: 'html',
data: {'ajax-query': 'true'}
success: function(data){
$('#divgallery').append(data);
}
});
})
Here comes the server code
if($i=0; $i<50;$i++){ echo '<img src="/img/' . $img . '">'; }
They are displayed all at once, after the server-side code is done.
How display images on each iteration?
Any tips, link or code example would be useful.
Firstly, on the server site return the image links in such way that they can be retrieved individually. I recommend JSON fromat.
$res = array();
if($i=0; $i<50;$i++){ $res[] = '<img src="/img/' . $img . '">'; }
echo json_encode($res);
Secondly, after you get the data you have to add the images one by one, but with a delay between the additions.
success: function(data){
delayAppend($("#divgallery"), data, 0);
}
And the delayAppend function would be something like:
function delayAppend($div, data, index){
if(index >= data.length)
return;
$div.append(data[index]);
setTimeout(function(){ delayAppend($div, data, index+1); }, 500);
}
Here is a demo of the delayAppend function: http://jsfiddle.net/s7Q8W/
Note: Code not fully tested.
I am trying to make an image upload where the JavaScript posts DataURI of an image via AJAX and the PHP receives it to decode it into an image.
The problem is, everything is working fine except that the end product is not an image file.
Please have a look at the following example code.
JavaScript:
dataString='encodedimg='+e.target.result.match(/,(.*)$/)[1]+'&type='+type;
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
data: dataString,
success: function(data){
//print success message
});
PHP:
$encodedimg = $_POST['encodedimg'];
file_put_contents('asdf.png', base64_decode($encodedimg));
There is no problem with $_POST['encodedimg'] as it produces the right image using online base64 converter. So I am assuming that there is a misuse with file_put_contents() or base64_decode().
Appreciate the help!
To read image on PHP i used a function like this
function rcd($data) {
$p = strpos($data, ',');
$d = base64_decode(substr($data, $p+1));
$rfn = md5(mt_rand(1,123123123));
file_put_contents($rfn, $d, LOCK_EX);
return $rfn;
}
Usage example:
$img_file_name = rcd($_POST['image_data']);
On JS part it is tricky (different browsers, etc). First of all You need to have the image data. Now You do not precise how this is sourced and the code example does not give a hint. We can assume some options
Simple You get dataString properly populated by whatever means neccesary, then Your example should basically work
imgdata = .... // any means of getting the data
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
});
Not so simple You have a Canvas object on the screen which was populated by any means and You want to send that data. Whatever above is true, however the way to get image data would be
var canv = document.getElementById('id_of_canvas');
imgdata = canv. toDataURL('image/jpeg', 0.88); // last arg is quality
However, as some browsers (mobiles) might not be so lucky to support this, you might want to find JPEGEncoder for JS and add it, along with the code below, to Your project.
var tdu = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function(type,param1)
{
var res = tdu.apply(this,arguments);
if(res.substr(0,11) != "data:image/")
{
var encoder = new JPEGEncoder();
return encoder.encode(this.getContext("2d").getImageData(0,0,this.width,this.height), (param1 ? param1*100 : 88));
}
else return res;
}
Hope this helps!
FOr #Marcin Gałczyński:
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
}
})
I think jQuery.ajax didnt have image_data jQuery.ajax
So I'm making a website for a client, and the client has tons of photos from tons of different bands they photographed in the 80s and 90s that they would like to try and sell.
Instead of making a page for each band (theres over 100) like the previous site did, I am trying to make one page that uses Javascript/PHP to change the image directory to that band when the text for that band is clicked.
So far, I am able to use a PHP function to find photos in the slideshow folder, but I have been unable to update this function to search through a sub directory in the slideshow folder. (For example, when 'Metallica' is clicked, I empty #imageGal, and then I would like to append all the new metallica images from the metallica folder to the gallery).
My PHP code is:
<?php
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
This PHP code seems to work great.
I get the images using this JQuery code:
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
When a user clicks on a band (ie Metallica), this code is executed.
$('.options').mousedown(function() {
var name = $(this).attr('id');
//$('#output').html(name);
$.ajax({
type: "POST",
url: "slideshow/getimages.php",
data: {
imageDir: name
}, success: function(msg){
alert( "Data Saved: " + msg );
}
});
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
});
I am unable to get the $imagesDir variable to change, but if I were to manually enter "Metallica" in $imagesDir = "Metallica" variable, it loads those images perfectly.
Can anyone offer any help/advice? I've been at this for a many hours now. Thanks for anything!
Unless you have register_globals on then you need to reference the variable through the global $_POST array. $_POST['imagesDir'] instead of $imagesDir.
However I would state in it's current form it would be a very bad idea to simply replace it as someone could attempt to exploit your code to list any directory on the server.
You should append the parent directory to prevent an exploit. Something like this:
EDIT you have to chdir() to the path before glob will work. I've updated my code below.
<?php
$imagesDir = $_SERVER['DOCUMENT_ROOT']; // this is the root of your web directory
$images = array();
// and this line ensures that the variable is set and no one can backtrack to some other
// directory
if( isset($_POST['imagesDir']) && strpos($_POST['imagesDir'], "..") === false) {
$imagesDir .= "/" . $_POST['imagesDir'];
chdir($imagesDir);
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
}
echo json_encode($images);
?>
I'm not an ajax expert but you seem to be posting imageDir.
So your PHP code should be looking for $_POST['imageDir'].
<?php
$imagesDir = $_POST['imageDir'];
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
Does this solve it?