php variable pass to javascript using getJSON() - javascript

i want to pass a php variable to javascript
on php(getStatus.php) i'm using json_encode like this
$resultFin = array();
if (strpos($status,'Scan is complete') === true){
$resultFin[] = 1;
}
else{
$resultFin[] = 0;
}
echo json_encode($resultFin);
echo "$status";
and i want get resultFin value on javascript so i wrote below code
echo '<script type="text/javascript">
$(document).ready(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
var refreshId = setInterval(function() {
$.post("scanner/getStatus.php", {testId:' . "$testId" . ',chkCnt:' . "$chkCount" . ',rxss:' . "$rxss" . ',sxss:' . "$sxss" . ',sqli:' . "$sqli" . ',basqli:' . "$basqli" . ',autoc:' . "$autoc" . ',idor:' . "$idor" . ',dirlist:' . "$dirlist" . ',bannerdis:' . "$bannerdis" . ',sslcert:' . "$sslcert" . ',unredir:' . "$unredir" . ',clamav:' . "$clamav" . '}, function(data){$("#status").html(data)});
console.log("dfdfdf");
$.getJSON("scanner/getStatus.php", function(data){
var fini;
fini = data;
console.log(fini);
if( fini == 1){
clearInterval(refreshId);
}
});
}, 500);
$.ajaxSetup({ cache: false });
});</script>';
i have checked it using brakepoint console.log("dfdfd");
but not getting into getJSON method and don't get resultFin value
how to fix this code?
i want resultFin value using in javascript

Your getStatus.php should look like:
$resultFin = array();
if (strpos($status,'Scan is complete') === true){
$resultFin['scan_completed'] = true;
}
else{
$resultFin['scan_completed'] = false;
}
echo json_encode($resultFin);
So on frontend you can use fini.scan_completed which will be true or false.

Related

how to stop infinite loop when using callback inside while-loop in js

so i'm creating a game like Connect 4 which ask an input from a user but the problem i'm facing is that i used callback(readline.question) function inside a while loop whenever i start the code it start infinite loop without asking a question from a user. how i can pause it for a while until user answer?
I've to solve this without using async/await.
function fetchColumn(player, callback) {
io.question(`Player ${player}, which Column? `, line => {
console.log(`You requested "${line}"`);
chosen_column = line;
callback();
});
}
let connect4 = new Connect4();
connect4.makeBoard(numRows, numCols, winLength);
while (game_over == 0) {
connect4.printBoard();
fetchColumn(current_player,()=>{
console.log(`you entered ${chosen_column}`);
if (chosen_column != 'Q' && chosen_column != 'q') {
move_status = connect4.place_piece(chosen_column, current_player);
x_in_a_row_status = connect4.x_in_a_row(current_player);
if (move_status == 0) {
// Further code-------
This is what i'm getting in terminal.
Player 1, which Column?
A B C D E F G
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
Player 1, which Column?
A B C D E F G
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
----------Keep repeating----------
If you want to call an asynchronous function in a loop, you can either use while in combination with await:
function fetchColumnAsync(player) {
return new Promise(function(resolve, reject) {
io.question(`Player ${player}, which Column? `, line => {
console.log(`You requested "${line}"`);
chosen_column = line;
resolve();
});
});
}
let connect4 = new Connect4();
connect4.makeBoard(numRows, numCols, winLength);
while (game_over == 0) {
connect4.printBoard();
await fetchColumnAsync(current_player);
console.log(`you entered ${chosen_column}`);
...
}
or recursion in combination with a callback function:
function loop() {
if (game_over == 0) {
connect4.printBoard();
fetchColumn(current_player, () => {
console.log(`you entered ${chosen_column}`);
...
loop();
});
}
}
let connect4 = new Connect4();
connect4.makeBoard(numRows, numCols, winLength);
loop();
But you cannot combine while with a callback, because the second iteration of the while loop starts synchronously, before the callback function can be invoked asynchronously. In other words, it gives an infinite loop.

Can't get the real size of the image in HTML with JS [duplicate]

This question already has answers here:
JavaScript: Get image dimensions
(9 answers)
Closed 2 years ago.
I have an image of a ball that I get from outer resource and I need to get the size of the image (height and width) for further calculations, but what I tried it shows 0 (but it's 40px actually)
Here is the whole code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Ball to center</title>
<style>
#field {
width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball {
position: absolute;
}
</style>
</head>
<body>
<div id="field">
<img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div>
<script type="text/javascript">
let field = document.getElementById('field');
let ball = document.getElementById('ball');
console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);
console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);
</script>
</body>
</html>
The problem with your approach, is that the code is executed before the page is loaded. As seen in here, you can do something like this with vanilla javascript to wait until page is loaded.
let field = document.getElementById('field');
let ball = document.getElementById('ball');
window.onload = () => {
console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);
console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);
};
You should only check the size of the image after it loads. You could use the loaded property of the image element to see if it's already loaded, otherwise attach a handler to the load event.,
let ball = document.getElementById('ball');
const checkImgSize = el => {
console.log(`natural height and width: ${el.naturalHeight} - ${el.naturalWidth}`);
console.log(`client height and width: ${el.clientHeight} - ${el.clientWidth}`);
};
if( ball.loaded )
checkImgSize(ball);
else
ball.addEventListener('load', function(){ checkImgSize(this) }, { once: true });

Dynamically include JavaScript from external file - PHP

Thanks in advance for your help. I am having a hard time keeping my codebase clean. I want to avoid intermixing PHP, HTML, and CSS.
Currently, my main site is broken down into numerous smaller tabs. The PHP code for these tabs is dynamically included after an ajax call is made.
elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) {
include 'templates/custom/'.$center."/".$section."/".$tab.".php";
}
It works great but I would also like to dynamically include JavaScript from an external file. In my mind it would work like this,
elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) {
include 'templates/custom/'.$center."/".$section."/".$tab.".php";
include 'templates/custom/'.$center."/".$section."/".$tab.".js";
}
How can I dynamically include javascript based on what tab the user wants to go to while still keeping the javascript separated by tab in individual files.
I have spent the entire day looking into this issue and keep coming across examples that look like this,
echo "<script language='javascript' type='text/javascript'>";
echo "alert('hello worldio');";
echo "</script>";
$URL="page.php";
echo "<script>location.href='$URL'</script>";
This site is a single page application. THanks again!
Just print the <script> tag to include it:
print '<script src="templates/custom/'.$center.'/'.$section.'/'.$tab.'.js'" type="text/javascript"></script>';
Javascript files cannot be included by php function. Use the below code
elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) {
include 'templates/custom/'.$center."/".$section."/".$tab.".php";
$file_path = "javascript external file path"; // replace with correct file path
?>
<script language="JavaScript" type="text/javascript" src="<?php echo $file_path;?>"></script>
<?php } ?>
hi in my case i use module base template that seprated to smaller parts.i have 3 main UI part in my site
1.public site js for all templates jquery,bootstrap ,... that use in all templates must put here
2.each style or template has a js folder that all public js file of this templates must be there
3.each module in template has js folder that js special for that module must be there
i do it for css too.in fact when i load a module check all of this folders by
array_slice(scandir($st_css_style_public_path), 2)
and create css link or js script and print final string of addresses in my page.
but some times you need to inject a peace of code directly into your page i use a folder and a file with name of plugins->plugins.php put all piece of script there get it's content and print it into my page
`$st_plugins .= (file_exists($st_plugin_style_public_path) ) ? file_get_contents($st_plugin_style_public_path) : ' ';
all of my render method in my view is this :
public function render($address, $data = '', $cache = 1, $showstyle = 1) {
$data['LINKPREFIX'] = '/' . $this->current_holding_unique_name
. '/'
. $this->current_lang;
if (isset($address)) {
$path = explode('/', $address);
$path[0] = $path[0];
$path[1] = $path[1];
}
$template = $this->twig->loadTemplate($path[0] . DS . $path[1] . '.twig');
if ($showstyle) {
$css_links = '';
$js_links = '';
$st_plugins = '';
//##################################################
//########################## CREATING CSS,JS ADDRESS
//##################################################
//####### SITE PUBLIC CSS & JS FILES
$st_js_public_path = '.' . DS . PUBLIC_DIR . DS . $this->set_address($path[0]) . 'js';
$st_css_public_path = '.' . DS . PUBLIC_DIR . DS . $this->set_address($path[0]) . 'css';
if (file_exists($st_js_public_path) && is_dir($st_js_public_path)) {
$ar_public_jsfile_list = array_slice(scandir($st_js_public_path), 2);
foreach ($ar_public_jsfile_list as $js_file_name) {
$js_links .= $this->create_css_js_link($st_js_public_path . DS . $js_file_name, 'js');
}
}
if (file_exists($st_css_public_path) && is_dir($st_css_public_path)) {
$ar_public_cssfile_list = array_slice(scandir($st_css_public_path), 2);
foreach ($ar_public_cssfile_list as $css_file_name) {
$css_links .= $this->create_css_js_link($st_css_public_path . DS . $css_file_name, 'css');
}
}
//####### STYLE PUBLIC CSS & JS & PLUGINS FILES
$st_js_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'js';
$st_css_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'css';
$st_plugin_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'plugins' . DS . 'plugins.php';
if (file_exists($st_css_style_public_path) && is_dir($st_css_style_public_path)) {
$ar_cssfile_list = array_slice(scandir($st_css_style_public_path), 2);
foreach ($ar_cssfile_list as $css_file_name) {
$css_links .= $this->create_css_js_link($st_css_style_public_path . DS . $css_file_name, 'css');
}
}
if (file_exists($st_js_style_public_path) && is_dir($st_js_style_public_path)) {
$ar_jsfile_list = array_slice(scandir($st_js_style_public_path), 2);
foreach ($ar_jsfile_list as $js_file_name) {
$js_links .= $this->create_css_js_link($st_js_style_public_path . DS . $js_file_name, 'js');
}
}
$st_plugins .= (file_exists($st_plugin_style_public_path) ) ? file_get_contents($st_plugin_style_public_path) : ' ';
//####### MODULE CSS & JS FILES
$st_js_style_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'js';
$st_css_style_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'css';
$st_plugin_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'plugins' . DS . 'plugins.php';
if (file_exists($st_css_style_path) && is_dir($st_css_style_path)) {
$ar_cssfile_list = array_slice(scandir($st_css_style_path), 2);
foreach ($ar_cssfile_list as $css_file_name) {
$css_links .= $this->create_css_js_link($st_css_style_path . DS . $css_file_name, 'css');
}
}
if (file_exists($st_js_style_path) && is_dir($st_js_style_path)) {
$ar_jsfile_list = array_slice(scandir($st_js_style_path), 2);
foreach ($ar_jsfile_list as $js_file_name) {
$js_links .= $this->create_css_js_link($st_js_style_path . DS . $js_file_name, 'js');
}
}
$st_plugins .= (file_exists($st_plugin_path) && $showstyle ) ? file_get_contents($st_plugin_path) : ' ';
//################################################
//################################################
//################################################
//################################################
//# # # CREATING CSS,JS ADDRESS
$data['VARCSSADDR'] = $css_links;
$data['VARJSADDR'] = $js_links . $st_plugins;
$data['VARURL'] = '/';
$data = array_merge($data, lang_translate::$lang);
$template->display($data);
} else {
//$ar_langpropr = language::$ar_lanuage[session::get('current_lang')];
//$data['lang_code'] = $ar_langpropr['lang_code'];
$data = array_merge($data, lang_translate::$lang);
return $this->twig->render($address . '.twig', $data);
}
}
i am using twig template engine so there are some unrelated code to your question here;else part is for ajax call.
conclusion:
1-you can use this structure to add or delete file from a module as easy as copy or delete a file from it's folder.
2- you can use it to create correct js or css to create address by ajax and print it in your code
i hope it helped you and don't hesitate to as more question if you need
PHP include()'s are server-side.
JavaScript is client-side.
Therefore, you cannot use include() on a JavaScript.
However, if you would like to load a JavaScript with a URL that you want, use this:
$url = "JAVASCRIPT URL HERE";
echo('<script src="'. $url .'"></script>');

php javascript autopopulated image gallery

I get the error message syntax error missing ; before statement at "var galleryarray=new Array();" . "\n"; here is the php code
function returnimages($dirname=".") {
$pattern="\.(jpg|jpeg|png|gif|bmp)$";
$files = array();$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){
echo 'galleryarray[' . $curimage .']=["' . $file . '"];' . "\n";
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo "var galleryarray=new Array();" . "\n";
returnimages();
and here is the javascript:
var galleryarray=new Array();
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "slideshow_images/"+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
window.onload=function(){
setInterval("rotateimages()", 2500)
}
i just don't see my mistake any help with this problem would be appreciated
klein
Replace your below line:
echo "var galleryarray=new Array();" . "\n";
with the following line:
echo "<script>var galleryarray=new Array();</script>";
You are adding a JS code without script tag so you need to add this tag.
EDITED:
echo 'galleryarray[' . $curimage .']=["' . $file . '"];' . "\n";
You also have error in the above line replace it with the below line:
echo '<script>galleryarray["' . $curimage .'"]=["' . $file . '"];</script>';

How can I write PHP code into JavaScript/Ajax?

I want to know how to write a pice of PHP code into JavaScript/Ajax.
This is my PHP code:
if ($folder = opendir('data/Tasklist/')) {
while (false !== ($file = readdir($folder))) {
if ($file != '.' && $file != ".."){
$data=file_get_contents("data/Tasklist/".$file);
$poc=explode(";",$data);
echo '<li class="taskli">
<button id="'. $file . '" class="Del"> Delete </button>
'. $poc[0] . " " . $poc[1] . '<div class="hidinfo">' . $poc[2] . '</div></li>';
}
}
closedir($handle);
}
And i want to write : id="'. $file . '" inside this code:
$.post( "data/remove.php",{HERE})
Since you're storing the $file variable in the <button> id, you can grab it from there:
$('.Del').click(function(){
var file = $(this).attr('id');
$.post( "data/remove.php",{id:file});
return false;
});

Categories