I have an image loading function in a js file.
It loads images from 1.jpg to a specified number (let's say 20).
What I would like to do instead of specifying a number, is find out how many images are in the folder and then use that as the specified number.
I know it is possible using GLOB in PHP, but AFAIK you can't use PHP in a js file?
function loadpics(url){
var txt,i,j;
j=20
//j=count(glob("images/" + url + "/*",GLOB_BRACE)); PHP file count here.
txt= "<span id=\"lar\">«</span><img id=\"main-img\" src=\"images/" + url + "/1.jpg\"/><span id=\"rar\">»</span><div id=\"scroller\">";
for (i=1;i<j;i++)
{
txt += "<img src=\"images/" + url + "/t/" + i + ".jpg\"/>";
}
document.getElementById("sidebar-b").innerHTML=txt + "</div>";
}
So how can I get the number of files from the url I pass to my loading picture function?
Or is there a better way?
Instead of relying on the pictures being sequentially ordered, use a foreach loop or create a script that merely echos the filenames as JSON for javascript to request
<?foreach(array_map('basename',glob('memes/*.jpg')) as $value){?>
<img src='memes/<?=htmlentities($value,ENT_QUOTES|ENT_XML1|ENT_SUBSTITUTE,"UTF-8",true)?>' style='height:200px;'/>
<?}?>
or
<?
if(isset($_GET['pic_list'])){
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array_map('basename',glob('memes/*.jpg')),JSON_PRETTY_PRINT);
exit;
}
?>
<div id='pic_list'></div>
<script>//<![CDATA[
(()=>{
var
xhr=new XMLHttpRequest()
,list=document.getElementById('pic_list');
xhr.onload=()=>{
var frag=new DocumentFragment();
xhr.response.forEach((v)=>{
var img=document.createElement('img');
img.src='memes/'+v;
img.style.height=200;
frag.appendChild(img);
});
list.appendChild(frag);
};
xhr.open("GET","?pic_list");
xhr.responseType="json";
xhr.send();
})();
//]]></script>
Related
I have created a QR code generating website. QR code is generated through PHP QR code generator library
by using this code
include_once "../phpqrcode/qrlib.php";
$PNG_TEMP_DIR = '../qrcodeImages/';
if (isset($_REQUEST['text'])) {
$content = $_REQUEST['text'];
$filename = $PNG_TEMP_DIR . 'qr' . md5($content) . '.png';
QRcode::png($content, $filename, 10);
echo $image = "<img class='img' src='qrcodeImages/" . basename($filename) . "'/>";
// $image_src = "qrcodeImage/" . basename($filename);
};
with this ajax call i append the QR code in the required div
$.ajax({
url: "code/single_input_to_qrcode.php",
type: "POST",
data: { text: jquery_plain_text },
success: (parms) => {
$("#downloadPart_img img").remove();
$("#downloadPart_img").append(parms);
}
});
and under QR code div I have placed a download button which is used to download the QR code
for downloading purpose I have used JavaScript library "File Saver"
code
var url = $("#downloadPart_img img").attr('src');
if (url == "img/white-qr-code.png") {
$("#error_msg_div").animate({ "top": "20px" });
error_msg = "Please generate a QR code before download";
error_msg_div.html(error_msg);
} else {
var file_name = url.substring(url.lastIndexOf('/') + 1);
url = "localhost/qrCodeGenerator/" + url;
saveAs(url, file_name);
}
But when user hit download button it show failed to download what kind of issue is that. I thinks this is because when the user hit the download button at the same time the file is saving in the folder so file is not available their at that time.
I have search a lot about that but I am fail to get its solution so now I am on this site to find solution so if some one now how to fix this problem so please help me.
Advance thanks
image of website and failed file at left bottom
I recover the content from a file on a external server. This file has many lines and when I get data it is on a single line.
I understand that when I visualize it on console '\n' and '\r' appear but when I download the file I hope still have many lines without those codes.
I have a Php file which bring back the content of the file and send the response to the JavaScript
$response_ads_txt = wp_remote_get('https://www.mywebsite.com/ads.txt');
if ( is_array( $response_ads_txt ) ) {
$body = $response_ads_txt['body'];
echo json_encode($body);
}
And Then I have Javascript which will download the file
jQuery.post(the_ajax_script.ajaxurl, data, function(response) {
console.log(response);
var a = document.createElement('a');
var data_type = 'data:text/plain;charset=utf-8';
a.href = data_type + ', '+encodeURIComponent(response);
a.download = 'ads.txt';
a.click();
});
I am trying to get a file that looks like
"line1
line2
line 3..."
And not like
"line1 \n\r line2..."
I solved the problem
I simply replaced
echo json_encode($body);
By :
echo $body;
Indeed there is no need to json_encode() the content as it's just text.
I have a web that draws a tree. inicio_pru.php creates a JSON which represents the tree.This JSON is passed to a JavaScript file for creting the tree.
inicio_pru.php, is called in two different moments, first , when the page is charged , it creates the JSON and passes it to example_pru.js in order this can draw it. 2nd, when the tree is already created, and user clicks a node of the tree, this invoques inicio_pru.php from example_pru.js with an object XMLHttpRequest and inicio_pru.php generates the JSON the same way as the 1rst time and this is sent to the XMLHttpRequest with an "echo" command.
It Works in the first case, but not in the second that generates the following error:
Unexpected token '
inicio_pru.php:
function main_p ($ID,$tipo_var,$desc_var,$idnodo,$t_ancestros) {
......
//Here, $arbol is saved in the correct format
if ($tipo_var=='BIFURCADORES'){
$file = fopen("archivo.txt", "w");
//$file = fopen($desc_var.".txt", "w");
fwrite($file, $arbol . PHP_EOL);
fclose($file);
}
return $arbol;
}
//main program
if (!is_null($idnodo)) {
// main_p , has saved $arbol with each field of the JSON in double quotes
$arbol=main_p($ID,$tipo_var,$desc_var,$idnodo,$t_ancestros);
//this sentence has saved $arbol at the discwith each field of the JSON without double quotes
exec('echo '.$arbol. ' >>/tmp/pista11', $output, $error);
//This is sent to example1_json_pru.js throght an objet XMLHttpRequest
echo $arbol;
}
else
$arbol=main_p($ID,$tipo_var,$desc_var,$idnodo,$t_ancestros);
As you can see, $arbol, is saved in two files:
archivo.txt , correct, it place each field in double quotes, but in pista11, fileds appear without these double quotes:
archivo.txt , (correct):
{"id":"53530","name":"Bifurcadores <ul ....
pista11 , (incorrect):
{id:53530,name:Bifurcadores <ul ......
In inicio_pru.php at the "else" sentence, $arbol is passed to another .php , that sends it to .js example_pru.js, and it works:
grafos_template_otro_json_fr_pru.php:
<!-- Files -->
<script language="javascript" type="text/javascript" src="../mapas/assets/js/example1_json_pru.js"></script>
<script type="text/javascript">
var datos=<?php echo $arbol ; ?>;
var ID=<?php echo $ID ; ?>;
var tipo_var=<?php echo $tipo_var ; ?>;
</script>
</head>
<body onload="init(datos,1,ID,tipo_var);">
(init is una function of example1_json_pru.js)
However, when init_pru.php is called from the XMLHttpRequest and it pases $arbol to example1_json_pru.js this way, it doesn't work, and generates the error mencioned before:
XMLHttpRequest:
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.onclick = function(){
var http = new XMLHttpRequest();
var url = "inicio_pru.php";
var params = "idnodo="+ node.id + "&ID=" + ID + "&id_arbol=" + tipo_var;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
//astonishingly, alert shows the fields of the JSON in quotes despite pista11 (file saved just before sending $arbol XMLHttpRequest object), showed them wihthout double quotes
alert (http.responseText);
//This is the sentence that generates error:
json=JSON.parse(http.responseText);
st.loadJSON(json);
//compute node positions and layout
st.compute();
//optional: make a translation of the tree
st.geom.translate(new $jit.Complex(-200, 0), "current");
st.onClick(node.id);
}
}
};
Could you please help me? Thank you very much indeed
the issue is that your json has invalid format.
archivo.txt , (correct):
{"id":"53530","name":"Bifurcadores
pista11 , (incorrect):
{id:53530,name:Bifurcadores
in above example you can see you are missing " " in variables and values.
Background - I'm calling a JSON feed via jQuery's AJAX method. No issues here. One of the values in the feed points to an image URL on Instagram and I then render the image in html.
Here's the problem - most of the Instagram URLs come back fine and the image renders on my html page as expected but a couple of URLs return 404 errors and therefore render no image.
My question - is there a way to check for that 404 error and tell the code to do something else?
Code -
var $SS__image = j.mainasset;
$output += '<img src="' + $SS__image + '" />';
What I want to achieve -
var $SS__image = j.mainasset;
if($SS__image.ERROR === '404'){
$output = '';
}else{
$output = '<img src="' + $SS__image + '" />';
}
Is this possible? Thanks in advance!
How about
var $img = $("<img/>");
$img.on("error",function() {
$(this).remove();
});
$output.append($img);
$img.attr("src",$SS__image); // in this order
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!