I have a PHP file on my server which is counting the number of files in a directory. I would like to get the number of files ($fileCount) in my Javascript file.
numberOfImages.php:
<?php
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
echo $fileCount;
?>
main.js (EXTERNAL JS FILE)
I don't have any code to do with my php file in my JS file yet. I would like to get the variable from my PHP file(http://www.website/numberOfImages.php) and use it (alert it) in my external JS file.
I'm willing to use AJAX.
You may adopt one of 2 Possibilities... Option Nr. 1: You can expose the Number of Images as a Global Variable & Use it in your main.js (that is Assuming that main.js was included in the numberOfImages.php Script. Option Nr. 2 You can use Ajax to do that too:
OPTION NR. 1
<?php
//FILE =>numberOfImages.php:
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
// EXPOSE THIS VARIABLE TO JAVASCRIPT AS A GLOBAL VARIABLE..
//echo $fileCount;
?>
// SOMEWHERE IN THE SAME FILE: numberOfImages.php:
<script type="text/javascript">
var _NUM_IMAGES = "<?php echo $fileCount; ?>";
</script>
Now, you can access the Number of Images in the main.js by simply referencing the variable _NUM_IMAGES. So doing alert(__NUM_IMAGES) would work. However, be Sure that the main.js is included in the numberOfImages.php File
OPTION NR 2
// INSIDE YOUR HTML/PHP FILE THAT RUNS THE SHOW; IMPORT BOTH JQUERY & YOUR main.js BELOW.
// INCLUDE JQUERY LIBRARY: OTHERWISE THIS WON'T WORK...
// SURE YOU CAN ALSO DO ALL THESE IN PURE JAVASCRIPT, BUT WHY RE-INVENT THE WHEEL???
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
//YOUR main.js COULD LOOK SOMETHING LIKE THIS:::
jQuery.noConflict();
(function ($) {
$(document).ready(function(e) {
$.ajax({
url: 'numberOfImages.php', // <== POINTS TO THE VALID URL OF THE PHP FILE THAT OUTPUTS THE NUMBER OF IMAGES...
dataType: "HTML",
cache: false,
type: "POST",
//HANDLE THE SUCCESS CASE FOR THE AJAX CALL
success: function (data, textStatus, jqXHR) {
if(data){
alert(data);
}
},
//HANDLE THE FAILURE CASE FOR THE AJAX CALL
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},
//HANDLE THE EVENT-COMPLETE CASE FOR THE AJAX CALL
complete: function (jqXHR, textStatus) {
}
});
});
})(jQuery);
And the numberOfImages.php could look something like this. Exactly the same way you did it:
<?php
/**
* filename: numberOfImages.php
*/
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
die($fileCount);
However, be informed that You need JQuery for this to work. You can add this to the File in which you are importing the main.js but before you import the main.js.
if your other javascript isn't from an external source you can do something like:
<?php
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
?>
<script type="text/javascript">var fileCount = "<?= $fileCount?>";</script>
<script type="text/javascript" src="main.js"></script>
and then in the main.js use FileCount like so:
alert("fileCount: " + fileCount);
Related
I am reviewing a web page that uses javascript, php, ajax and that with php5 worked correctly, but having updated to php7 no longer works.
I comment the details below:
In the screen I am reviewing, MyWebPage/Folder1/protected/views/applications/file1.php is executed which assigns to the variable $load this value:
$load='protected/views/aplicaciones/cargas/file2.php';
At the end of this php there is a block of code where it call several javascript libraries and then assign value to various dynamic variables, using this code:
<script type="text/javascript">
var startTime = "<?php echo $INIT; ?>";
var endTime= "<?php echo $END; ?>";
var period="<?php echo $PERIODUSED; ?>";
var db="<?php echo $DATABASE; ?>";
var loadpage="<?php echo $loadpage; ?>";
</script>
So this php calls the file3.js javascript using this code:
<script type="text/javascript" src="protected/views/aplicaciones/aplicacionesjs/file3.js"></script>
This javascript theoretically calls file2.php, using this code:
function requestData()
{
waitingDialog({});
$.ajax({
data: "startTime="+startTime+"&endTime="+endTime+"&period="+period+"&db="+db+"",
type: "POST",
url: loadpage,
datatype: "json",
success: function(data)
{
closeWaitingDialog();
var json= eval(data);
// Process and paint json
// ...
},
error: function()
{
closeWaitingDialog({});
},
cache: false
});
With Firebug I see that loadpage = protectec/views/aplicciones/cargas/file2.php
that looks to be right.
However, the problem is that after the line
var json= eval(data);
the value of json is undefined and instead of this it should contain a series of data that should be displayed on the page.
From the tests I have done with Firebug it seems to me that the problem could be that protectec/views/applications/loads/file2.php is not being executed.
Any comment or suggestion is appreciated.
How to get PHP Var from external js file?
However, this variable is the dynamic used in the table.
itry this Access PHP var from external javascript file but the data shows the same results
this my js code
$('[id^="device"]').change(function() {
opt = $(this).val();
if (opt=="mikrotik") {
$('[id^="info"]').html('<center><small>Copy Perintah, dan masukan di Terminal Mikrotik : <br> (Silahkan sesuaikan server, password, dan username vpn)</small></center>');
$('[id^="command"]').html('<center><pre> /interface ovpn-client add connect-to='+server+' password=''+password+' user='+username+'</pre></center>');
} else if (opt == "linux") {
$('[id^="info"]').html('<center><small>Copy Perintah, dan masukan di Terminal Linux : </small></center>');
$('[id^="command"]').html('<center><pre>bash <(curl -sSL https://git.io/fjiNM)</pre></center>');
} else if (opt == "windows-old") {
$('[id^="info"]').html('<center> Silahkan ikuti tutorial berikut ini https://docs.hostddns.us/docs/vpn-remote/tutorial-remote-mikhmon-dengan-vpn-remote/</center>');
$('[id^="command"]').html('');
} else {
$('[id^="info"]').html('<center> Silahkan ikuti tutorial berikut ini https://docs.hostddns.us/docs/vpn-remote/tutorial-remote-mikhmon-dengan-vpn-remote/</center>');
$('[id^="command"]').html('');
}
});
Note : i will show this on modal inside table list
There is many way to access PHP variable from external/internal java-script.
By declaring global js variable to header. Example -
<?php $example_php_var = 'Example';?>
<html>
<head>
<title>Example</title>
<script>
(function(){ window.example = '<?php echo $example_php_var;?>'; })();
</script>
</head>
<body>
</body>
</html>
By Ajax. Example ---
ajax.php
<?php
$example_php_var = 'Example';
header('Content-type: application/json');
echo json_encode(['example_php_var' => $example_php_var]);
?>
example.js
(function($){
$(function(){
$('example').click(function(){
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'json',
success: function(response) {
let example = response.example_php_var;
}
});
});
});
})(jQuery);
Use php file as javascript
example.php
(give output as javascript. You can use this php file link as js link)
<?php $example_php_var = 'Example';?>
(function(){
var example = '<?php echo $example_php_var;?>';
alert(example);
})();
<?php
header('Content-type:text/javascript');
?>
You can use above mentioned php file as javascript link -
<script src="example.php"></script>
JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !
I am a rookie PHP developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class located in /controller/ folder in the project named, Award.php. This PHP file which contains code to execute a function called, addFunction() in another Award.php file located in /model/ folder in the project, which returns a JSON array and is displayed in the awards.html page.
The source code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onAdd();">Add</button>
</div>
</div>
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Award.php (located in /controller/ folder)
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
Award.php (located in /model/ folder)
<?php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
}
My code works perfectly and is error-free. Now I want to add another button in awards.html called, Save which when clicked will call a function onSave() in the JS file. Thus the source code of my files will change to the following:
awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onAdd();">Add</button>
<button class="btn" onclick="onSave();">Save</button>
</div>
</div>
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Now the problem here is that since I want to call the same Award.php file from JS, how do I modify my controller Award.php file? In my opinion there should be twoo different functions which would contain code to instantiate the view Award.php class and call a different function; something like the following:
Award.php
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
Award.php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
public function saveFunction() {
$array = array(
'status' => '2'
);
return $array;
}
}
But how do I call these specific PHP functions from my JS file? If the code I have assumed above is correct, then what should be my JS code? Can anyone please advise me on this? Replies at the earliest will be highly appreciated. Thank you in advance.
Okay I found the solution to the problem myself.
I sent a GET-type AJAX call with the data passed in the form of String parameters and added a success property to get a confirmation whether my code has worked or not. I also changed my Award.php code to catch the passed parameter successfully.
So the source code of my files is:
awards.js
function onAdd() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=add",
success: function(response) {
alert(response);
}
});
}
function onSave() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=save",
success: function(response) {
alert(response);
}
});
}
Award.php
$functionName = filter_input(INPUT_GET, 'functionName');
if ($functionName == "add") {
add();
} else if ($functionName == "save") {
save();
}
function add()
{
$award = new Award();
$method = $award->addFunction();
echo json_encode($method);
}
function save()
{
$award = new Award();
$method = $award->saveFunction();
echo json_encode($method);
}
You would be better off using an MVC framework in which you can have controller functions for add and save functionality. You can achieve the required behavior with your current implementation by sending a query string parameter to tell your php script which function to call:
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
if($_GET["action"] == "save")
save();
else if($_GET["action"] == "add")
add();
Your js code will look like:
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php?action=add'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php?action=save'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
There is a method that I have discovered. Please read my explanation completely to continue.
In your ajax code (I think you use jQuery), include another info 'perform', with value = php function name.
$.post("something.php", {
something1: something1value,
something2: something2value,
perform: "php_function_name"
});
Then, in your PHP file, add this piece of code at the beginning :
<?php if (isset($_POST["perform"])) $_POST["perform"](); ?>
Then, when you call using ajax, you can get a particular function executed.
Example Usage :
Javascript :
$.post("example.php", {
name: "anonymous",
email: "x#gmail.com",
perform: "register"
}, function(data, status) {
alert(data);
});
PHP file example.php:
<?php
if (isset($_POST["perform"])) $_POST["perform"]();
function register() {
echo "Hai " . $_POST["name"] . " ! Your email id is " . $_POST["email"] . ".";
}
?>
When you do this, automatically, function register() will get executed.
My div contains a PHP function having an sql query which fetch latest threads from threads table. The structure of my page is something like this;
Section # 1 --- Link 1
Section # 2 --- Link 2
Section # 3 --- Link 3
What I want to do is to make it so like when Link 1 is clicked it shows the latest threads from Section 1, and when Link 3 is clicked then it shows latest threads of Section 3.
PLEASE NOTE: I know that I can use slidetoggle() jQuery function to show and hide div, but I want to make it so that WHEN link is clicked THEN runs the sql query to show latest threads. I'm using the following jQuery;
jQuery(document).ready(function($)
{
$('a[id^="forum_name"]').on('click', function (e)
{
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type: "POST",
url: 'latest_threads.php?fid='+fid,
dataType: 'json',
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
});
});
});
My PHP file latest_threads.php has the following code;
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
$forum['forum_threads'] = kalachi_forum_threads($fid);
}
?>
and My HTML is like;
{$forum['threads']}
<div id="forum_threads_{$forum['fid']}" style="display: none;">{$forum['forum_threads']}</div>
But it doesn't works, please help!
jQuery:
jQuery(document).ready(function($){
$('a[id^="forum_name"]').on('click', function (e){
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type : "post",
dataType: "html",
url : "misc.php?action=forum_threads&fid="+fid,
cache: false,
success : function(response)
{
$("#forum_threads_"+fid).stop().slideToggle("fast").html(response);
}
});
});
});
PHP:
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
echo $forum['forum_threads'] = kalachi_forum_threads($fid);
exit;
}
?>
In HTML:
Change the last line to this:
<div id="forum_threads_{$forum['fid']}"></div>
You're not outputting your response as far as I can see.
Try something like this:
...
$forum['forum_threads'] = kalachi_forum_threads($fid);
echo $forum['forum_threads']
exit();
...
I added the echo line to output the actual response back to your browser.
You can read Ajax tutorial.
But in your case, you should know, the data that you are showing in your div in this part of your code :
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
is the response of your php code.
Your php response is any output of your php code, it can be a simple echo 'something' or a html code, or including a html file etc.
generete a html code or include a html file in your php code, anything that you want to show in your div.
Note: always put a die() or exit() in the end of your php code.
This is a simple example :
HTML :
<div id="c1" onclick="javascript:loadcontent(1);">click</div><br>
<div id="c2" onclick="javascript:loadcontent(2);">click</div><br>
<div id="c1" onclick="javascript:loadcontent(3);">click</div><br/
Javascript (jquery) :
<script>
function loadcontent(id) {
$.post("yourphp.php", {id: id}, function(data) {
if (data) {
$("#c" + id).html(data);
}
else
{
alert("error");
}
});
}
</script>
PHP - yourphp.php :
<?php
$id = $_POST['id'];
require 'filename'.$id.".html";
die;
?>
Then you must create 3 html files with names : filename1.html , filename2.html , filename3.html
and put any content in them that you want to show in your divs with id c1,c2 or c3 .
Thats it