I must pass array from JS to PHP using $.post(), create file using array and download it.
Using this pass array:
$('#csv').click(function () {
$.post(
window.location + "crawler/save_to_file",
{
dane: wynik //array
});
});
Now in PHP using this:
$tablica=$_POST['dane'];
$filename = "export-to-csv.csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Expires: 0");
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($tablica))
foreach($tablica as $row) {
if(!$heading) {
fputcsv($fh, array_keys($row));
$heading = true;
}
fputcsv($fh, array_values($row));
}
fclose($fh);
But when click on button to create and download file, nothing happens.
Thanks
CODE UPDATE
JS file:
$.ajax({
url: window.location + "crawler/",
type: "POST",
dataType: "json",
data: {
wartosc: zmienna
},
success: function (odp) {
wynik = odp; //array
tab = JSON.stringify(odp);
$.post(window.location + "crawler/return_data",
{
data: tab
},
function (data) {
$('#wynik').html(data);
$('.pobierz').show();
}
)
}
})
$('.button').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_csv" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
});
$form.appendTo('body').submit();
});
And var_dump array in PHP file:
function save_to_csv()
{
$tablica=$_GET['dane'];
var_dump($tablica);
}
return: "Undefined index: dane"
EDIT
$tablica must be $_POST not $_GET
This can be done with AJAX but you need to use the File api.
So you do something like this:
$.post("csv.php", {
dane: wynik //array
}, function(response){
var blob = new Blob([response], { type:'text/csv' });
alert(URL.createObjectURL(blob));
});
The url you get from the alert, contains your csv file.
And of course if you want to go directly to the file you replace the alert with:
window.location.href=URL.createObjectURL(blob);
UPDATE
If you want to use a custom filename, there is a way to mask the url generated by URL.createObjectURL(), by using an a element.
We than can use the new HTML5 attribute download which allows us to mask the url.
Here is the updated code:
$.post("csv.php", {
dane: wynik //array
}, function(response){
var blob = new Blob([response], { type:'text/csv' }),
a = document.createElement('a'),
url = URL.createObjectURL(blob);
// Put the link somewhere in the body
document.body.appendChild(a);
a.innerHTML = 'download me';
a.href = url;
// Set our custom filename
a.download = 'myfilename.csv';
// Automatically click the link
a.click();
});
Are you forced to use AJAX to send that array to your PHP code? If yes, it is not really possible.
If not, instead of your AJAX call, you could build a hidden form with hidden inputs containing your array items and submit it via JavaScript.
UPDATE
Short example for form built with JS:
$('#csv').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_file" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
});
$form.appendTo('body').submit();
});
Related
I am trying to convert .HEIC image to .JPG using libheif.
libheif converts image on client side browser window only. So in order to save the image i converted image to base64 and then performed ajax to save the image using file_put_contents.
this.canvas.toBlob(function(blob) {
var extension = FILE_EXTENSIONS[blob.type] || ".bin";
var basename = this.filename.replace(/\.[^/.]+$/, "");
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, basename + extension);
return;
}
var readers = new FileReader();
var base64image;
readers.readAsDataURL(blob);
readers.onload = function () {
var base64image = readers.result; // data <-- in this var you have the file data in Base64 format
// console.log(base64image);
// call ajax
var formData = new FormData();
formData.append('filename', basename);
formData.append('avatar', readers.result);
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
}
});
};
return;
// this.downloads.appendChild(dlink);
// dlink.click();
// URL.revokeObjectURL(url);
}.bind(this), format);
When i convert a single image then it works fine. But if i try to convert in loop it does not works.
Before completing js conversion, my php loop runs (I think this is the issue) So i tried php function sleep() and js set timeout(), But unfortunately none worked.
(function() {
var demo = new HeifDemo(libheif);
<?php $img_array = array('demo/1.heic', 'demo/2.heic', 'demo/3.heic');
foreach ($img_array as $img) : ?>
function saveImage(subject, callback) {
demo.loadUrl(subject);
callback();
}
saveImage('<?php echo $img; ?>', function() {
// demo.saveImage();
setTimeout( function(){
demo.saveImage();
}, 2500 );
});
//});
<?php sleep(4); endforeach; ?> }).call();
I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}
In my data storage folder is a JSON file. I save the device id to the local storage of the broswer:
//Store deviceID in local storage on button click
function store(){
var inputDeviceID= document.getElementById("deviceID");
localStorage.setItem("deviceID", inputDeviceID.value);
}
I get the device id with a javascript function and push it with ajax into my php script to load the corresponsing data:
function localstoragecheck(){
if (localStorage.getItem("deviceID") === null) {
//alert('no');
}
else {
//alert('yes');
var deviceIDcookie = localStorage.getItem("deviceID");
$.ajax({
url: '/',
data: {'deviceID': deviceIDcookie},
dataType: 'jsonp',
complete : function(){
// alert(this.url)
$.getJSON("/sigfoxdata/" + deviceIDcookie + ".json", function(json) {
console.log(json); // this will show the info it in firebug console
});
}
});
}
}
PHP code for searching the json file and decode it:
$FOLDER = '../sigfoxdata/';
$dir = scandir($FOLDER);
$file = $_GET['deviceID'].'.json' ?: 'DEMO.json';
$fileUrl = $FOLDER.$file;
$file = fopen($fileUrl, "rip");
$lines = fread($file, filesize($fileUrl));
$data = json_decode($lines)->{'data'};
But this is not working, how can I get data from the ajax request in the PHP script?
I'm using dropzoneJS to upload multiple file and then taking image name back from action file using Json_Encode to attach these name to input field for submitting these input fields with other input fields in form. I could do it for one image but couldnt get any way for multiple images(2 images).
<div class=" dropzone dz-clickable photoBox" id="addPhoto">
<input type="hidden" id="img1">
<input type="hidden" id="img2">
</div>
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#addPhoto", {
acceptedFiles:'image/jpeg,image/jpg,image/png,image/gif',
url: 'uploadProImage.php',
maxFiles: 2, // Number of files at a time
maxFilesize: 2, //in MB
maxfilesexceeded: function(file) {
alert('You have uploaded more than 2 Image. Only the first two file will be uploaded!');
},
addRemoveLinks: true,
removedfile: function(file) {
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
success: function (response) {
var x = JSON.parse(response.xhr.responseText);
$('#img1').attr('value',x.img);
$('#img2').attr('value',x.img);
}
});
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once('simpleImage_class.php');
$ds= DIRECTORY_SEPARATOR;
$dir= 'ProPics';
$targetPath = $dir . $ds;
if (!empty($_FILES)) {
$img_name = $_FILES['file']['name'];
$img_tmp_name = $_FILES['file']['tmp_name'];
$img_ext = pathinfo($img_name, PATHINFO_EXTENSION);
$chng_name = 'img-'.time().rand(0,10).".".$img_ext;
$array = array("img"=>$chng_name);
echo json_encode($array);
$targetFile = $targetPath. $chng_name;
if(move_uploaded_file($img_tmp_name,$targetFile))
{
$image = new SimpleImage();
$image->load($targetFile);
$image->resizeToWidth(110);
$image->resizeToHeight(140);
$image->save($targetPath.'thumb-'.$chng_name);
}
}
You should do it with AJAX JSON.
When a file is uploaded, you should return a AJAX JSON response and the response JSON should have all info you need to use in view.
Then you should use the success method to use the JSON responce like this-
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
//Do what you need to do with the JSON u have received
}
};
});
And surely you should parse JSON and put them in the actual view with this like this-
var array = JSON.parse(string);
array.forEach(function(object) {
//do what u need to do
});
So whole JS code for response will be like this -
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
var array = JSON.parse(string);
array.forEach(function(object)
{
//do what u need to do
});
}
};
});
i am trying to disaplay slider images dynamically by fetching all images names from slider_images folder and append it to .
<script>
var dir = "images/slider_images";
var fileextension = ".jpg";
$.ajax({
url: dir,
type: "POST",
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var url = this.href;
var filename = url.substring(url.lastIndexOf('/')+1);
//alert(filename);
$(".slides").append($("<li><img src=" + dir +"/"+ filename + "></img></li>"));
});
}
});
</script>
Finally i solve this issue by using json.
first i create getimages.php file and read directory in that file and get all images names and store that name in array.
getimages.php
<?php
$filenameArray = array();
$handle = opendir(dirname(realpath(__FILE__)).'/images/slider_images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/slider_images/$file");
}
}
echo json_encode($filenameArray);
?>
call getimages.php from page where you want load images dynamically.
index.php
$.ajax({
url: "getimages.php",
dataType: "json",
success: function (data) {
alert("success");
$.each(data, function(i,filename) {
alert(filename);
$('.slides').append('<li><img src="'+ filename +'" class="drop_shadow" alt="Slider Image 1" /></li>');
});
}
});
this is working perfectly for me. i you want please try this. this is very simple and easy way to load images from folder using ajax