I am trying to display multiple images coming from a remote server on a single page, the page is a html file where putting php blocks wouldn't be doing anything to get thing I want
Using PHP version 5.6, the code for the php is
$dir = "uploads/image/dashed/";
$files = scandir($dir);
foreach ($files as $file)
{
if ( is_file($dir. $file) ){
echo $file;
}
}
the ajax response code is:
$(document).ready(function(){
$.ajax({
async: true,
type: 'POST',
url: 'folder.php',
success: function(data){
$("#imageContent").html(data).append("<br/>");
var images = data.split("\n");
for (var i = 0, j = images.length; i < j; i++){
$("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>");
}
}
});
});
all I keep getting from the server is
1354876944ABF.jpg_MG_0085.jpg
and an empty image place holder (not two, just the one) for where the image
and the image address is showing two image names stuck together in one link
uploads/image/dashed/1354876944ABF.jpg_MG_0085.jpg
where the response link should be on two (for this example) different lines and images where the <img> is on the html inside the ajax call
Try This,
$dir = "uploads/image/dashed/";
$files = scandir($dir);
$i = 1;
$count = count($files);
foreach ($files as $file){
if(is_file($dir. $file)){
if($i == $count){
echo $file;
}else{echo $file.'|||';
}
}
$i++;}
and change ajax to:
$(document).ready(function(){
$.ajax({
async: true,
type: 'POST',
url: 'folder.php',
success: function(data){
$("#imageContent").html(data).append("<br/>");
var images = data.split("|||");
for (var i = 0, j = images.length; i < j; i++){
$("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>");
}
}
});
});
thats using ||| as a delimiter.
EDIT: now it should work properly,
EDIT2: changed $i = 0 order, added $i++; at the end
scandir() is already giving you an array, so why not just json_encode it and return this? unset() any output that is not a valid file:
$files = scandir($dir);
$count = count($files);
for($i = 0; $i < $count; $i++) {
if ( !is_file($dir. $file) ){
unset($files[$i]);
}
}
echo json_encode($files);
then in your success block:
success: function(data){
$("#imageContent").html(data).append("<br/>");
var i,
json = JSON.parse(data);
for (i in json){
$("#imageContent").append("<img src='uploads/image/dashed/" + json[i] + "' width='300'>");
}
}
Related
I have auto load more on page scroll down.
My jQuery/ajax is working but it is auto loading only first 2 pages on scroll down. There are more pages/records but it stuck after 2nd page loads.
I cannot understand the issue.
Somebody please help me out. My php and java code is given below
just played around with the same moving lines up and down but no use.
<?php
$pxe = $_GET['pname'];
$sxe = $_GET['sname'];
?>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
getresult.php
<?php
include('inc/db.php');
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($sql);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql." limit ".$start.",".$perPage;
$faq = $dba3->query($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = mysqli_num_rows($faq);
}
$output = '';
if(!empty($faq)) {
$output .= '<input hidden class="pagenum" value="'.$page.'" />';
$output .= '<input hidden class="total-page" value="'.$pages.'" />';
while ($row = $faq->fetch_assoc()) {
$output .= $row["ename"];
} }
print $output;
?>
no errors just loader image keeps moving
The key is to get the row count from the initial sql, before applying the limit, something like:
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($query);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql . " limit " . $start . "," . $perPage;
$faq = $dba3->query($query);
You should add async : false, in your ajax request.
url: url,
async : false,
type: "GET",
data: {rowcount:$("#rowcount").val()},
Your browser needs to wait for the response before the next request is sent.
i've case to use variable more the one like code bellow :
function upload(iddata,ring)
{
//variable 1
dataString ="iddata="+iddata+"&ring="+ring+""; // variable 1
//variable 2
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
// i want put both variabel in ajax like this
$.ajax({
data: {formData,dataString}, //variable 1 and 2 in group
});
}
please how source is True
You should handle your whole data as an object only, and not mix it as a string and a array in a object. In this case you would not get the expected data in your receiver.
You could change it like this:
function upload(iddata, ring) {
var data = {
iddata: iddata,
ring: ring,
formData: new FormData()
};
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
data.formData.append("file[]", file, file.name);
}
$.ajax({
data: data
});
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MyBird extends CI_Controller {
/**
* Index Page for this controller.
function add_bird()
{
// get user id posted
$iddata=empty($_POST['iddata']) ? '' : $_POST['iddata'];
$ring=empty($_POST['ring']) ? '' : $_POST['ring'];
//echo json_encode(array('uploaded' => 'Oke Bos'));
if ( ! empty($_FILES))
{
$config['upload_path'] = "./assets/images/uploads";
$config['allowed_types'] = 'gif|jpg|png|mp4|ogv|zip';
$this->load->library('upload');
$files = $_FILES;
$number_of_files = count($_FILES['file']['name']);
$errors = 0;
// codeigniter upload just support one file
// to upload. so we need a litte trick
for ($i = 0; $i < $number_of_files; $i++)
{
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = "Ring".$ring._.$Random_Number; //new file name
$config['file_name'] = $NewFileName;
$_FILES['file']['name'] = $files['file']['name'][$i];
$_FILES['file']['type'] = $files['file']['type'][$i];
$_FILES['file']['tmp_name'] = $files['file']['tmp_name'][$i];
$_FILES['file']['error'] = $files['file']['error'][$i];
$_FILES['file']['size'] = $files['file']['size'][$i];
// we have to initialize before upload
$this->upload->initialize($config);
if (! $this->upload->do_upload("file")) {
$errors++;
}
}
if ($errors > 0) {
echo $errors . "File(s) cannot be uploaded";
}
}
}
}
in controller i put code like bellow, but the filen can't move upload
var imgAlums = window.document.getElementsByClassName("imgAlu");
var photos= [];
for (var i = 0; i < imgAlums.length; i++) {
photos.push(imgAlums[i].currentSrc);
}
//the photos array is filled //photos[0]=
data:image/;base64,/9j/4AAQSkZJRgABAQAAAQA...;
//photos[1]=data:image/;base64,/9j/4AAFWEJDKWMDCIWUEIOD...;
$.ajax({
type: 'POST',
url: '<?= URL_PROYECTO_SEGURO ?>/panel/assets/php/generateZipPhotos.php',
data: {"photos": JSON.stringify(photos)},
success: function (data) {
console.log(data);
alert("Operacion realizada con exito");
}
});
PHP code:
$nameZip = "test.zip";
$zip = new ZipArchive();
$zip->open($nameZip, ZipArchive::OVERWRITE);
$zip->addEmptyDir("Photos");
$photos= json_decode($_POST["photos"], true);
for ($i = 0; $i < count($photos); $i++) {
$data = $photos[$i];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$zip->addFromString("Photos/Photo" . $i . ".png", $data);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$nameZip");
header("Content-Transfer-Encoding: binary");
readfile($nameZip);
unlink($nameZip);
But does not generate the zip file correctly.
[edit]The zip file is generated but this has nothing inside. The problem is when you write in the zip file. The photo is misspelled
I have tasks that I want to do synchronously; but I don't want to freeze the browser. There could be 1---N tasks.
Below is the synchronous version. It works as expected but freezes the browser.
How can I do this using jQuery deferred object to do these task in order but not lock browser.
NOTE: The server I am request to does NOT allow for 2 requests at once. They need to run one after the other once the request is finished in exact order.
<?php
for ($k = 0;$k<count($partial_transactions);$k++)
{
?>
$("#formCheckout_<?php echo $k; ?>").ajaxSubmit({
success:function(response)
{
var data = response.split("&");
var processed_data = [];
for(var i = 0; i < data.length; i++)
{
var m = data[i].split("=");
processed_data[m[0]] = m[1];
}
$("#please_wait").hide();
if (processed_data.CmdStatus != 'Approved')
{
var message = decodeURIComponent(message);
message = processed_data.TextResponse.replace(/\+/g, ' ');
toastr['error'](<?php echo json_encode(lang('sales_attempted_to_reverse_partial_transactions_failed_please_contact_support'));?>, <?php echo json_encode(lang('common_error')); ?>);
}
else
{
toastr['success'](<?php echo json_encode(lang('sales_partial_credit_card_transactions_voided')); ?>, <?php echo json_encode(lang('common_success')); ?>);
}
},
cache: true,
headers: false,
async: false
});
<?php
}
?>
Try this:
var counter = 0;
// Build up an array of all forms that are to be submitted sequentially.
var forms = [
<?php
for ($k = 0;$k<count($partial_transactions);$k++){
if($k == 0){
echo "#formCheckout_{$k}";
}else{
echo ", #formCheckout_{$k}";
}
}
?>
];
// Start the request
make_next_request(forms[counter]);
function make_next_request(form){
form.ajaxSubmit({
success:function(response)
{
var data = response.split("&");
var processed_data = [];
for(var i = 0; i < data.length; i++)
{
var m = data[i].split("=");
processed_data[m[0]] = m[1];
}
$("#please_wait").hide();
if (processed_data.CmdStatus != 'Approved')
{
var message = decodeURIComponent(message);
message = processed_data.TextResponse.replace(/\+/g, ' ');
toastr['error'](<?php echo json_encode(lang('sales_attempted_to_reverse_partial_transactions_failed_please_contact_support'));?>, <?php echo json_encode(lang('common_error')); ?>);
}
else
{
toastr['success'](<?php echo json_encode(lang('sales_partial_credit_card_transactions_voided')); ?>, <?php echo json_encode(lang('common_success')); ?>);
}
// Now chain request onto next form.
if(counter < forms.length){
counter++;
make_next_request(forms[counter]);
}
},
cache: true,
headers: false,
async: false
});
}
You could just put it all in a web worker that handles all the data, so the UI thread doesn't get interrupted (but you'll have to give the user some indication that the data is loading.)
See the web worker API for more info, but basically, web workers are native browser objects that allow you to have multi-threaded operations. In other words, your operations can run in the background while the user still interacts with the web page, and then when the operations are complete, they can notify the UI thread (the thread the user is currently on.)
This CPU-intensive data loading that you're talking about seems like a perfect use case for such an API.
I ended up doing it like this. The intensive part is server side. So I took some suggestions and came up with this. (Using recursion)
<script>
var num_transactions_to_void = <?php echo count($partial_transactions); ?>;
var max_index = num_transactions_to_void - 1;
if (num_transactions_to_void > 0)
{
void_sale_request(0);
}
function void_sale_request(index)
{
if (index > max_index)
{
return;
}
$("#formCheckout_"+index).ajaxSubmit({
success:function(response)
{
var data = response.split("&");
var processed_data = [];
for(var i = 0; i < data.length; i++)
{
var m = data[i].split("=");
processed_data[m[0]] = m[1];
}
$("#please_wait").hide();
if (processed_data.CmdStatus != 'Approved')
{
var message = decodeURIComponent(message);
message = processed_data.TextResponse.replace(/\+/g, ' ');
toastr['error'](<?php echo json_encode(lang('sales_attempted_to_reverse_partial_transactions_failed_please_contact_support'));?>, <?php echo json_encode(lang('common_error')); ?>);
}
else
{
toastr['success'](<?php echo json_encode(lang('sales_partial_credit_card_transactions_voided')); ?>, <?php echo json_encode(lang('common_success')); ?>);
}
void_sale_request(index + 1);
},
cache: true,
headers: false
});
}
</script>
I have my json being passed to the php file as follows.
JAVASCRIPT
$.ajax({
url: "/gallerytest/getimages.php",
type: "POST",
dataType: "json",
data: {
imagesArray: imageArray.itemList,
action: "load"
},
success: function(imagesArray) {
for (var i = 0; i < imagesArray.length; i++) {
console.log('image ' + imagesArray[i]["src"]);
}
}
});
With the imagesArray being captured in the php file, I want to put it into an array. In my php I have this so far:
PHP
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case "test" : test();break;
case "load" : load();break;
// ...etc...
}
}
function load(){
$imagesArray = $_POST['imagesArray'];
$images = json_decode($imagesArray, true);
$imagesArr = array();
for ($i = 0; $i < count($images); $i++){
$image = array(
"src" => $images[$i]
);
$imagesArr[] = $image;
}
echo json_encode($imagesArr);
}
I am passing the array back for testing purposes where the javascript outputs the src of each element.
The ultimate goal which I would like help on too, should it not go beyond the call of duty, is in an SQL statement capture more images where the src does not match.
In essence:
SELECT * FROM images WHERE id_image NOT IN (imagesArray) ORDER BY rand() LIMIT 12
$.ajax({
url: "/gallerytest/getimages.php",
type: "POST",
dataType: "json",
data: {
"imagesArray": imageArray.itemList,
"action": "load"
},
success: function(imagesArray) {
for (var i = 0; i < imagesArray.length; i++) {
console.log('image ' + imagesArray[i]["src"]);
}
}
});
Please Pass the action and imagesArray tag in double quote