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>
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.
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
</script>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
PHP:
<?php
$name = $_POST['data'];
echo $name;
?>
It doesn't working...
try this out, i just did and worked fine
here's my js file
<html>
<head>
</head>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
<footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function() {
var val = $(this).val();
$.ajax({
// your uri, pay attention if the post is going to the right place
url: "try.php",
type: "POST",
// myVar = name of the var that you will be able to call in php
// val = your data
data: {'myVar': val}
});
});
});
</script>
</footer>
</html>
and here's my php
<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses
Make proper json string to send data. You are having extra ; there.
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
And get it with data key in php.
<?php
$name = $_POST['data'];
echo $name;
?>
Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.
<button id="example" name="name_example" value="some_value">
1</button>
$(document).ready(function () {
$('#example').click(function() {
var buttonValue = $(this).val();
$.ajax({
url: "try.php", //assuming that your html file is in the same folder as
//your php script.
type: "POST",
data: {'example': buttonValue}
});
});
});
look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/
In your .php file, which should be in the same folder as your html file doing the request you will have:
<?php
echo '<pre>'; print_r($_POST); die; // see if you now have those vars.
?>
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);
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
I would like to send 'ID' to JS function then send the same ID again from JS function to php function.
Please tell me what is the wrong in my code!
<script type="text/javascript">
function deleteclient(ID){ //I receive the ID correctly until now!
var x = "<?php deleteclient11('ID');?>";
return false;
}
</script>
<?php
function deleteclient11($x)
{
echo "$x";
}
?>
You need to use AJAX, it's easy with jQuery or another library, so I'll demonstrate with jQuery.
javascript
var deleteClient = function(id) {
$.ajax({
url: 'path/to/php/file',
type: 'POST',
data: {id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
};
php file
<?php
if (isset($_POST['id'])) {
deleteClient11($_POST['id']);
function deleteClient11($x) {
// your business logic
}
}
?>
More info: jQuery.ajax()